15

map怠惰にする方法はありますか?それとも、Pythonに組み込まれている別の実装がありますか?

私はこのようなものを機能させたい:

from itertools import count

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

forもちろん、上記のコードは終了しませんが、内部に任意の条件(またはより複雑なロジック)を入力して、ある時点で停止したいと思います。

4

2 に答える 2

43

itertools.imapPython 2.xで使用するか、Python3.xにアップグレードします

また、はるかにpythonicである単純なジェネレータ式を使用することもできます。

foo = (x**2 for x in count())
于 2013-03-08T01:24:14.980 に答える
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.
于 2013-03-08T01:24:02.870 に答える