Python中的惰性映射函数

15 投票
2 回答
10007 浏览
提问于 2025-04-17 18:21

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

我想要让下面这样的代码可以正常工作:

from itertools import count

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

当然,上面的代码是不会结束的,但我希望能在 for 循环里放入任何条件(或者更复杂的逻辑),然后在某个点停止。

2 个回答

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.
43

在Python 2.x中可以使用 itertools.imap,或者你可以升级到Python 3.x。

你也可以使用一个简单的生成器表达式,这样写起来更符合Python的风格:

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

撰写回答