Is there a difference between #39;and#39; and #39;amp;#39; with respect to python sets?(and 和 amp; 有区别吗关于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.
...
这篇关于'and' 和 '&' 有区别吗关于python集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:'and' 和 '&' 有区别吗关于python集?
基础教程推荐
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
