gpt4 book ai didi

Python惰性迭代器

转载 作者:太空狗 更新时间:2023-10-30 00:42:09 25 4
gpt4 key购买 nike

我试图了解如何以及何时对迭代器表达式求值。以下似乎是一个懒惰的表达:

g = (i for i in range(1000) if i % 3 == i % 2)

这个,但是在构造上失败了:

g = (line.strip() for line in open('xxx', 'r') if len(line) > 10)

我没有名为“xxx”的文件。不过,既然这东西懒,为什么这么快就失败了?

谢谢。

EDI:哇,我偷懒了!

g = (line.strip() for i in range(3) for line in open(str(i), 'r'))

最佳答案

来自documentation :

Variables used in the generator expression are evaluated lazily in a separate scope when the next() method is called for the generator object (in the same fashion as for normal generators). However, the in expression of the leftmost for clause is immediately evaluated in the current scope so that an error produced by it can be seen before any other possible error in the code that handles the generator expression.

关于Python惰性迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2249651/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com