2013-03-08 59 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.