【问题标题】:Is there a difference between 'and' and '&' with respect to python sets?关于 python 集,'and' 和 '&' 之间有区别吗?
【发布时间】:2013-05-22 15:40:40
【问题描述】:

check if dictionary key has empty value 的问题我得到了很好的帮助。但我想知道and&在python中是否有区别?我认为它们应该是相似的?

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 在我投票结束后,问题的设置部分被添加为编辑。
  • 是的。我正在写这件事。当我使用“and”而不是“&”时出现keyerror

标签: python set


【解决方案1】:

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

> 2 > 1 and 2 > 3
True

& 是位运算符,用于执行位与运算:

> 255 & 1
1

更新

对于set operations& 操作符等价于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

对于它的价值,还请注意,根据Dictionary view objects 的python 文档,dict1.viewkeys() 返回的对象是一个“类似集合”的视图对象:

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

...

dictview & other

将dictview和另一个对象的交集作为一个新集合返回。

...

【讨论】:

  • 你应该使用set 而不是Set
  • 很好,谢谢。来自文档:The built-in set and frozenset types were designed based on lessons learned from the sets module.
  • & 不是按位完全。例如,您不能使用它来比较浮点数或浮点数与 NaN。
【解决方案2】:
  • 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 doc)

【讨论】:

    【解决方案3】:

    是的and 是逻辑与,而& 是按位与。见例子 -

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

    第一个结果是由于短路。 Python 测试 1 并发现它为真并返回 2。但是,第二部分执行 01 (Binary 1) & 10 (Binary 2) 因此评估为 00 (1 & 0, 0 &1) ,即 0。

    【讨论】:

      【解决方案4】:

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

      7 & 3
      => 3
      
      True and False
      => False
      

      【讨论】:

      • 注意:这个答案是在 OP修改问题之前发布的,表示要在集合上应用运算符
      【解决方案5】:
      >>> 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                            |
      +-------------------------------------------------+---------------------------------------+
      

      【讨论】:

        猜你喜欢
        • 2015-02-05
        • 1970-01-01
        • 1970-01-01
        • 2012-02-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-27
        • 1970-01-01
        相关资源
        最近更新 更多