繁体   English   中英

为什么在 Python 中使用相同的代码会得到不同的结果?

[英]Why do I get different results with the same code in Python?

L = [1,2,3]

print(len(L) == 3 & len(L) > 2)
print(len(L) > 2 & len(L) == 3)

^^ 顶部的评估为真,底部的评估为假? 为什么? 他们不是一样的吗?

更详细地解释: &执行按位比较,但它也比关系运算符具有更高的优先级(与逻辑and不同)。

len(L) == 3 & len(L) > 2

这将比较len(L) == (3 & len(L))以及(3 & len(L)) > 2链式关系运算符- 3 & len(L)只计算一次)。 由于len(L)等于 3,因此3 & len(L)的计算结果也为 3(按位与)。 3 == 33 > 2 ,所以这是真的。

len(L) > 2 & len(L) == 3

类似地: 2 & len(L)计算结果为 2。 2 > 2是假的(并且为了更好的衡量, 2 == 3也是假的),所以这评估为假。

您不想将&用于逻辑AND运算符,请使用单词and

>>> L = [1,2,3]
>>> print(len(L) == 3 and len(L) > 2)
>>> print(len(L) > 2 and len(L) == 3)
True
True

暂无
暂无

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

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