在Python集合中,“and”和“&”有什么区别吗?

6

我对问题检查字典键是否为空值得到了很好的帮助。但是我想知道在Python中and&有什么区别?我认为它们应该是相似的吗?

dict1 ={"city":"","name":"yass","region":"","zipcode":"",
   "phone":"","address":"","tehsil":"", "planet":"mars"}

whitelist = {"name", "phone", "zipcode", "region", "city",
             "munic", "address", "subarea"}

result = {k: dict1[k] for k in dict1.viewkeys() & whitelist if dict1[k]}

这不是重复的问题,该问题还涉及集合操作。 - jamylak
3
@jamylak 在我投票关闭之后,问题的设置部分被添加为编辑。 - Joachim Isaksson
是的。我正在写关于这个的内容。当我使用“and”而非“&”时,出现了KeyError错误。 - hjelpmig
5个回答

11

and是一个逻辑运算符,用于比较两个值,例如:

> 2 > 1 and 2 > 3
True

& 是一个位运算符,用于执行按位 AND 操作:

> 255 & 1
1

更新

关于集合操作& 运算符等同于 intersection() 操作,并创建一个新的集合,其中包含 s 和 t 共有的元素:

>>> a = set([1, 2, 3])
>>> b = set([3, 4, 5])
>>> a & b
set([3])

"and仍然只是一个逻辑比较函数,如果传入一个set参数,它将把它视为非假值。如果两个参数都不是False,它也会返回最后一个值:"
>>> a and b
set([3, 4, 5])
>>> a and b and True
True
>>> False and a and b and True
False

值得一提的是,根据Python文档中关于字典视图对象的说明,由dict1.viewkeys()返回的对象是一个“类似集合”的视图对象:

dict.viewkeys()dict.viewvalues()dict.viewitems()返回的对象都是视图对象。它们提供了对字典条目的动态视图,这意味着当字典发生变化时,视图会反映这些变化。

...

dictview & other

返回字典视图与其他对象的交集作为一个新的集合。

...


2
你应该使用 set 而不是 Set - tacaswell
很好的发现,谢谢。来自文档:内置的 set 和 frozenset 类型是基于从 sets 模块中学到的教训设计的。 - Justin Ethier
& 不是完全按位运算符。例如,您不能使用它来比较浮点数或带有 NaN 的浮点数。 - user5920660

7
  • and 是逻辑与
  • & 是按位与

逻辑 and 如果两个值都为真,则返回第二个值。

对于集合,& 表示交集。

如果你执行以下操作:

In [25]: a = {1, 2, 3}

In [26]: b = {3, 4, 5}

In [27]: a and b
Out[27]: set([3, 4, 5])

In [28]: a & b
Out[28]: set([3])

这是因为 bool(a) == Truebool(b) == True,所以 and 返回第二个集合。& 返回集合的交集。 (set文档)

3

是的,and 是逻辑与,而 & 是按位与。请看下面的例子 -

>>> 1 and 2
2
>>> 1 & 2
0

第一个结果是由于短路现象引起的。Python测试1并发现它为真,然后返回2。但是,第二部分执行01(二进制1)和10(二进制2),因此计算结果为00(1&0,0&1),即0。


1

&是按位与运算符,and是布尔逻辑运算符。它们非常不同,不要混淆!例如:

7 & 3
=> 3

True and False
=> False

请翻译以下与编程有关的内容,从英文到中文。仅返回已翻译的文本:注意:此答案在 OP 修改问题之前发布,指出操作符需要应用于集合。 - Óscar López

1
>>> help('&')

+-------------------------------------------------+---------------------------------------+
| Operator                                        | Description                           |
+=================================================+=======================================+
| ``lambda``                                      | Lambda expression                     |
+-------------------------------------------------+---------------------------------------+
| ``if`` -- ``else``                              | Conditional expression                |
+-------------------------------------------------+---------------------------------------+
| ``or``                                          | Boolean OR                            |
+-------------------------------------------------+---------------------------------------+
| ``and``                                         | Boolean AND                           |
+-------------------------------------------------+---------------------------------------+
| ``not`` ``x``                                   | Boolean NOT                           |
+-------------------------------------------------+---------------------------------------+
| ``in``, ``not in``, ``is``, ``is not``, ``<``,  | Comparisons, including membership     |
| ``<=``, ``>``, ``>=``, ``<>``, ``!=``, ``==``   | tests and identity tests,             |
+-------------------------------------------------+---------------------------------------+
| ``|``                                           | Bitwise OR                            |
+-------------------------------------------------+---------------------------------------+
| ``^``                                           | Bitwise XOR                           |
+-------------------------------------------------+---------------------------------------+
| ``&``                                           | Bitwise AND                           |
+-------------------------------------------------+---------------------------------------+
| ``<<``, ``>>``                                  | Shifts                                |
+-------------------------------------------------+---------------------------------------+
| ``+``, ``-``                                    | Addition and subtraction              |
+-------------------------------------------------+---------------------------------------+
| ``*``, ``/``, ``//``, ``%``                     | Multiplication, division, remainder   |
|                                                 | [8]                                   |
+-------------------------------------------------+---------------------------------------+
| ``+x``, ``-x``, ``~x``                          | Positive, negative, bitwise NOT       |
+-------------------------------------------------+---------------------------------------+
| ``**``                                          | Exponentiation [9]                    |
+-------------------------------------------------+---------------------------------------+
| ``x[index]``, ``x[index:index]``,               | Subscription, slicing, call,          |
| ``x(arguments...)``, ``x.attribute``            | attribute reference                   |
+-------------------------------------------------+---------------------------------------+
| ``(expressions...)``, ``[expressions...]``,     | Binding or tuple display, list        |
| ``{key: value...}``, ```expressions...```       | display, dictionary display, string   |
|                                                 | conversion                            |
+-------------------------------------------------+---------------------------------------+

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接