'and' 和 '&' 有区别吗关于python集?
问题描述
我得到了很好的帮助 检查字典键是否有空值 .但是我想知道python中的 and
和 &
之间是否有区别?我认为它们应该是相似的?
I got very good help for question check if dictionary key has empty value . But I was wondering if there is a difference between and
and &
in python? I assume that they should be similar?
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]}
解决方案
and
是一个逻辑运算符,用于比较两个值,IE:
and
is a logical operator which is used to compare two values, IE:
> 2 > 1 and 2 > 3
True
&
是按位运算符,用于执行按位与运算:
&
is a bitwise operator that is used to perform a bitwise AND operation:
> 255 & 1
1
更新
关于设置操作,&code> 操作符等价于
intersection()
操作符,并创建一个包含 s 和 t 共有元素的新集合:
With respect to set operations, the &
operator is equivalent to the intersection()
operation, and creates a new set with elements common to s and t:
>>> a = set([1, 2, 3])
>>> b = set([3, 4, 5])
>>> a & b
set([3])
and
仍然只是一个逻辑比较函数,并将 set
参数视为非假值.如果两个参数都不为 False
,它也会返回最后一个值:
and
is still just a logical comparison function, and will treat a set
argument as a non-false value. It will also return the last value if neither of the arguments is False
:
>>> a and b
set([3, 4, 5])
>>> a and b and True
True
>>> False and a and b and True
False
对于它的价值,还请注意,根据 字典视图对象,dict1.viewkeys()
返回的对象是set-like"的视图对象:
For what its worth, note also that according to the python docs for Dictionary view objects, the object returned by dict1.viewkeys()
is a view object that is "set-like":
dict.viewkeys()
、dict.viewvalues()
和dict.viewitems()
返回的对象是视图对象.它们提供字典条目的动态视图,这意味着当字典更改时,视图会反映这些更改.
The objects returned by
dict.viewkeys()
,dict.viewvalues()
anddict.viewitems()
are view objects. They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes.
...
dictview &其他
将dictview和另一个对象的交集作为一个新集合返回.
Return the intersection of the dictview and the other object as a new set.
...
相关文章