有没有办法让 map
变得懒惰?或者是否有另一种内置在 Python 中的实现?
我想要这样的东西:
from itertools import count
for x in map(lambda x: x**2, count()):
print x
当然,上面的代码不会结束,但我想在 for
中输入任何条件(或更复杂的逻辑)并在某个点停止。
最佳答案
使用itertools.imap
在 Python 2.x 上或升级到 Python 3.x
你也可以只使用一个更 pythonic 的简单生成器表达式:
foo = (x**2 for x in count())
关于python - Python 中的延迟映射函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15285134/