Python 奇怪的迭代器行为

标签 python

我在这里回答了另一个问题: Query on [Python sum of number in array, ignoring sections of specific numbers]

在这个问题中,有一段类似的代码:

it = iter([4, 5, 6, 7, 8, 9])
print([x for x in it if x!=4 not in it]) #Output [5]

据我理解,迭代器就像一个列表,我们在访问每个元素后删除它们。 我还了解到,像 not in 这样的操作将循环遍历迭代器,直到找到它正在搜索的值。因此,在我们执行 3 not in iter([1, 2]) 的情况下,迭代器将为空,因为 not in 已循环遍历所有迭代器以确认未包含 3

因此,根据我的理解,for 循环的第一次迭代应该执行以下操作:

it = iter([4, 5, 6, 7, 8, 9])
for x in it:
    #Here it look like [5, 6, 7, 8, 9] and x is 4
    if x!=4 not in it:
        # So here we've done 
        #x!=4 => False 
        #then False not in it
        #Since False isn't in it the iterator should now be empty and we don't enter this if
        print(x)

#And there is'nt a second iteration since the iterator is empty dues to the if condition so
#the loop should end after the first iteration without anything printed

但是这段代码输出是 5 这到底是怎么可能的???
因此,如果有人可以详细解释到底发生了什么,我们将不胜感激!

旁注:
我也尝试过

  • (x!=4) 不在其中 ⇾ 输出为 4
  • x!=(4 不在其中) ⇾ 不输出任何内容

这让我想知道 python 是如何解释这个条件的,因为没有一个带括号的版本与不带括号的版本匹配。

最佳答案

所以,这里的问题是表达式:

x != 4 not in it

是隐式链接的,因为 comparison operators work 就是这样的。

这意味着它被评估为:

(x != 4) and (4 not in it)

由于 x != 4 在第一次迭代中为 False,因此它会短路并继续下一次迭代,而不评估其中的 4 >。在这种情况下,x == 5,并且它不会短路,并且它会耗尽迭代器检查5是否不在其中,在这种情况下,整个表达式为 True,并且它是结果列表中的唯一项目。

关于Python 奇怪的迭代器行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72049290/

相关文章:

python - 我的问答游戏中的draw()函数无法正常工作

python - 无法在 jupyter 笔记本中导入 psycopg2,但可以在 python3 控制台中导入

python - 根据类别乘以列

python - sqlalchemy connection.execute() 上的 UnicodeDecodeError 用于选择查询

python - 如何从时间序列数据中选择前 n 列而不是在 pandas 中使用 nlargest?

python - super() 为新式类引发 "TypeError: must be type, not classobj"

python - 这两种传递参数的方式有什么区别?

python - 如何使用 argparse 参数作为函数名

python - Pyreverse 未连接 UML 类图中的类

python - 为什么要调用 python 析构函数?