如果python迭代器返回可迭代对象,我如何将这些对象链接到一个大迭代器? [英] If a python iterator returns iterable objects, how can I chain those objects into one big iterator?
问题描述
我将在这里给出一个简化的例子。假设我在python中有一个迭代器,这个迭代器返回的每个对象本身都是可迭代的。我想获取这个迭代器返回的所有对象,并将它们链接到一个长迭代器中。是否有标准实用程序可以实现这一目标?
I'll give a simplified example here. Suppose I have an iterator in python, and each object that this iterator returns is itself iterable. I want to take all the objects returned by this iterator and chain them together into one long iterator. Is there a standard utility to make this possible?
这是一个人为的例子。
Here is a contrived example.
x = iter([ xrange(0,5), xrange(5,10)])
x
是一个返回迭代器的迭代器,我想链接所有x返回到一个大迭代器的迭代器。在这个例子中这样一个操作的结果应该是
等于xrange(0,10),它应该被懒惰地评估。
x
is an iterator that returns iterators, and I want to chain all the iterators returned by x into one big iterator. The result of such an operation in this example should be
equivalent to xrange(0,10), and it should be lazily evaluated.
推荐答案
您可以使用 itertools.chain.from_iterable
You can use itertools.chain.from_iterable
>>> import itertools
>>> x = iter([ xrange(0,5), xrange(5,10)])
>>> a = itertools.chain.from_iterable(x)
>>> list(a)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
如果您的版本没有(显然,它是2.6中的新功能),您可以手动执行:
If that's not available on your version (apparently, it's new in 2.6), you can just do it manually:
>>> x = iter([ xrange(0,5), xrange(5,10)])
>>> a = (i for subiter in x for i in subiter)
>>> list(a)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
这篇关于如果python迭代器返回可迭代对象,我如何将这些对象链接到一个大迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!