Python中的惰性映射函数

Python中的惰性映射函数,python,map,iterator,lazy-evaluation,Python,Map,Iterator,Lazy Evaluation,有没有办法让map变得懒惰?或者在Python中是否有其他内置的it实现 我想让这样的东西起作用: from itertools import count for x in map(lambda x: x**2, count()): print x 当然,上面的代码不会结束,但我只想在for中输入任何条件(或更复杂的逻辑),并在某个点停止。itetools.imap是惰性的 In [3]: itertools.imap? Type: type String Form:&l

有没有办法让
map
变得懒惰?或者在Python中是否有其他内置的it实现

我想让这样的东西起作用:

from itertools import count

for x in map(lambda x: x**2, count()):
    print x

当然,上面的代码不会结束,但我只想在
for
中输入任何条件(或更复杂的逻辑),并在某个点停止。

itetools.imap
是惰性的

In [3]: itertools.imap?
Type:       type
String Form:<type 'itertools.imap'>
Docstring:
imap(func, *iterables) --> imap object

Make an iterator that computes the function using arguments from
each of the iterables.  Like map() except that it returns
an iterator instead of a list and that it stops when the shortest
iterable is exhausted instead of filling in None for shorter
iterables.
[3]中的
:itertools.imap?
类型:类型
字符串形式:
文档字符串:
imap(func,*iterables)-->imap对象
生成一个迭代器,使用来自的参数计算函数
每一个伊特拉伯雷人。与map()类似,只是它返回
一个迭代器而不是一个列表,当最短的
iterable已耗尽,而不是在较短的时间内无填充
不可抗力。
在Python2.x上使用或升级到Python3.x

您也可以只使用一个简单的生成器表达式,它更像python:

foo = (x**2 for x in count())

请参见此处:。简而言之:要么使用生成器表达式,要么使用itertools模块。@RobertHarvey:链接不错。事实上,除了做
x*2
而不是
x**2
,这个博客非常适合这个问题@罗伯塔维:这篇文章写得很好。谢谢大家!+1用于推荐生成器表达式。无论您在哪里需要
lambda
map()
都不是一个好选择。谢谢您的回复。我只是尝试为这个问题制作一个更简单的代码示例(使用
map
)。