2013-03-08 62 views
8

有没有办法让map懒惰?还是有Python的内置的另一个实现?Python中的懒惰地图函数

我想是这样工作的:

from itertools import count 

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

当然,上面的代码不会结束,但我想刚进入任何条件(或更复杂的逻辑)的for内,在某个点停下来。

+1

看这里:知道什么时候是懒惰](http://davywybiral.blogspot.com/2008/08/python-know-when-to-be-lazy.html)。简而言之:使用生成器表达式或使用itertools模块。 – 2013-03-08 01:24:02

+0

@RobertHarvey:尼斯链接。事实上,除了'x * 2'而不是'x ** 2'之外,这个博客非常适合这个问题! – abarnert 2013-03-08 01:27:45

+0

@RobertHarvey非常好的文章。谢谢! – 2013-03-08 01:32:56

回答

27

上的Python 2.x的使用itertools.imap或升级到Python 3.x的

你也可以使用一个简单的生成器表达式是远远更Python:

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

+1用于推荐生成器表达式。无论你需要'lambda','map()'都不是一个好选择。 – 2013-03-08 01:36:03

+0

感谢您的回复。我只是试图为这个问题制作一个更简单的代码示例(当使用'map'时)。 – 2013-03-08 01:38:28

4

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.