Python lazy iterator

試著忘記壹切 提交于 2019-12-23 12:09:59

问题


I am trying to understand how and when iterator expressions get evaluated. The following seems to be a lazy expression:

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

This one, however fails on construction:

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

I do not have the file named 'xxx'. However, since this thing is lazy, why is it failing so soon?

Thanks.

EDI: Wow, I made a lazy one!

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

回答1:


From the 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.




回答2:


The iteration over the file returned by the call to open() is lazy. The call to open() is not.



来源:https://stackoverflow.com/questions/2249651/python-lazy-iterator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!