繁体   English   中英

字典中有var的怪异行为

[英]Weird behavior with var in dict

>>> x = { 'a' : 'b' , 'c' : 'd' }

>>>'a' and 'c' in x
True

>>>'a' and 'b' in x
False

>>>'b' and 'c' in x
True

如果in <dict>检查密钥,那么即使没有这样的密钥b ,查找b的最后一个密钥也返回true

您想要'b' in x and 'c' in x

您误会了and运算符的工作方式(并且您的运算符优先级有误)。 in的优先级高于and ,因此您的表达式被解析为:

if 'b' and ('c' in x):

与以下内容相同:

if 'c' in x:

因为bool('b')始终为True因为'b'是非空字符串。

这是python中运算符优先级

请注意,即使and优先级高于in ,您仍然不会得到想要的东西,因为('b' and 'c') in x会减少('b' and 'c') in x'c' in x因为'b' and 'c'返回'c'

重写表达式的一种方法是:

if all( key in yourdict for key in ('b', 'c') ):

仅需检查2个键就可以解决这个问题,但是如果您要检查更多的键,此功能将很快变得有用。

作为最后的评论,您可能正在尝试应用运算符链接(这确实很简洁)。 但是,有些运营商不能很好地进行链接( in就是其中之一)。 3 > 10 > 100 > 1000这样的表达式确实可以通过某种奇怪的蟒蛇黑魔法起作用。 以我的经验,关系运算符可以很好地链接('<','>','==','<=','> ='),但是大多数其他运算符都不以直观的方式进行链接。 一般来说,

a operator b operator c operator ...

等效于:

(a operator b) and (b operator c) and (c operator ...

这等效于您当前拥有的:

>>> 'a' and ('c' in x)
True

>>> 'a' and ('b' in x)
False

>>> 'b' and ('c' in x)
True

您想要这个:

>>> 'a' in x and 'c' in x
True

>>> 'a' in x and 'b' in x
False

>>> 'b' in x and 'c' in x
False

另外,您可以使用集合和<= (子集)运算符:

>>> set(['a', 'c']) <= set(x.keys())
True

>>> set(['a', 'b']) <= set(x.keys())
False

>>> set(['b', 'c']) <= set(x.keys())
False

在Python 2.7和更高版本中, set(['a', 'c'])可以替换为{'a', 'b'}

'c' in x 'b'为真, 'c' in x也为真。 (True and True) == True 您需要'b' in x and 'c' in x

and没有按照您的想法去做。

'a' and 'c' in x

手段:

bool('a') and ('c' in x)

意思是:

True and True

当然,这意味着True :)

您需要做:

('a' in x) and ('c' in x)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM