Grz*_*ała 10 python iterator generator python-itertools
给定一对对列表xys,将其解压缩为两个列表的Python成语是:
xs, ys = zip(*xys)
Run Code Online (Sandbox Code Playgroud)
如果xys是迭代器,我如何将其解压缩为两个迭代器,而不将所有内容存储在内存中?
假设你有一些可迭代的对:
a = zip(range(10), range(10))
Run Code Online (Sandbox Code Playgroud)
如果我正确地解释了你要求的东西,你可以使用itertools.tee以下方法为第一和第二代生成独立的迭代器:
xs, ys = itertools.tee(a)
xs, ys = (x[0] for x in xs), (y[1] for y in ys)
Run Code Online (Sandbox Code Playgroud)
请注意,这将在内存中保留您迭代其中一个与另一个之间的"差异".
如果你想独立于另一个使用一个迭代器,就没有办法避免将内容拉入内存,因为其中一个迭代器将进行而另一个迭代器不会进行(因此必须缓冲).
这样的东西允许你迭代对的"左项"和"右项":
import itertools
import operator
it1, it2 = itertools.tee(xys)
xs = map(operator.itemgetter(0), it1))
ys = map(operator.itemgetter(1), it2))
print(next(xs))
print(next(ys))
Run Code Online (Sandbox Code Playgroud)
...但请记住,如果只使用一个迭代器,另一个将缓冲内存中的项目,直到您开始使用它们.
(顺便说一下,假设Python 3.在Python 2中你需要使用itertools.imap(),而不是map().)
| 归档时间: |
|
| 查看次数: |
3362 次 |
| 最近记录: |