为什么这不能用作数组成员资格测试? [英] Why does this not work as an array membership test?
问题描述
我知道这是一种测试会员资格的奇怪方式,而且
<预><代码>>>>5 不在 [1, 2, 3, 4] 中真的是正确"的方式.让我困惑的是它的行为与两者不同
<预><代码>>>>([1, 2, 3, 4] 中的 5) == False真的和
<预><代码>>>>5 in ([1, 2, 3, 4] == False)类型错误...我是否遗漏了一些明显的东西?(在 Python 2.7 和 Python 3.4 中测试).
为了澄清,我理解最后三个片段.我在询问 first 代码段的行为,以及为什么不同.
这是一个链式比较.你可能知道你可以做到
1 <2<3
在 Python 中,它等价于 (1 <2) 和 (2 <3)
.(或许你没有.现在你知道了.)好吧,同样的事情适用于 in
和 ==
.
5 in [1, 2, 3, 4] == False
相当于
(5 in [1, 2, 3, 4]) and ([1, 2, 3, 4] == False)
由于 [1, 2, 3, 4]
不等于 False
,整个表达式的计算结果为 False
.
>>> 5 in [1, 2, 3, 4] == False
False
I get that this is a bizarre way to test membership, and that
>>> 5 not in [1, 2, 3, 4]
True
is the "correct" way. What confuses me is that its behavior is different from both
>>> (5 in [1, 2, 3, 4]) == False
True
and
>>> 5 in ([1, 2, 3, 4] == False)
TypeError ...
Have I missed something obvious? (Tested in Python 2.7 and Python 3.4).
To clarify, I understand the last three snippets. I am asking about the behavior of the first snippet, and why it is different.
This is a chained comparison. You may have known that you can do
1 < 2 < 3
in Python, and it's equivalent to (1 < 2) and (2 < 3)
. (Or maybe you didn't. Now you know.) Well, the same thing applies to in
and ==
.
5 in [1, 2, 3, 4] == False
is equivalent to
(5 in [1, 2, 3, 4]) and ([1, 2, 3, 4] == False)
Since [1, 2, 3, 4]
is not equal to False
, the whole expression evaluates to False
.
这篇关于为什么这不能用作数组成员资格测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!