'and' 和 '&' 之间有区别吗关于python集? [英] Is there a difference between 'and' and '&' with respect to python sets?

查看:43
本文介绍了'and' 和 '&' 之间有区别吗关于python集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在问题检查字典键是否为空值时得到了很好的帮助 .但是我想知道 python 中 and& 之间是否有区别?我认为它们应该相似?

dict1 ={"city":"","name":"yass","re​​gion":"","zipcode":"","电话":"","地址":"","tehsil":"", "planet":"mars"}whitelist = {"name", "phone", "zipcode", "region", "city",城市"、地址"、分区"}result = {k: dict1[k] for k in dict1.viewkeys() &白名单如果 dict1[k]}

解决方案

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

<代码>>2 >1 和 2 >3真的

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

<代码>>255 &11

更新

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

<预><代码>>>>a = 集合([1, 2, 3])>>>b = 集合([3, 4, 5])>>>一个&乙设置([3])

and 仍然只是一个逻辑比较函数,并且会将 set 参数视为非假值.如果两个参数都不是 False,它也将返回最后一个值:

<预><代码>>>>一个和一个设置([3, 4, 5])>>>a 和 b 和 True真的>>>假和 a 和 b 和真错误的


对于它的价值,还要注意根据 字典视图对象dict1.viewkeys()返回的对象是一个set-like"的视图对象:

<块引用>

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

...

dictview &其他

将 dictview 和其他对象的交集作为新集合返回.

...

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 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

Update

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 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


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":

The objects returned by dict.viewkeys(), dict.viewvalues() and dict.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 & other

Return the intersection of the dictview and the other object as a new set.

...

这篇关于'and' 和 '&amp;' 之间有区别吗关于python集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆