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集?
基础教程推荐
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
