問題描述
假設我們有一個返回列表(或有限迭代器)的迭代器(無限迭代器),例如由
Suppose we have an iterator (an infinite one) that returns lists (or finite iterators), for example one returned by
infinite = itertools.cycle([[1,2,3]])
什么是獲得迭代器(顯然是無限的)的一個好的 Python 習慣用法,它將從第一個迭代器返回每個元素,然后從第二個迭代器返回每個元素,依此類推.在上面的示例中,它將返回 1,2,3,1,2,3,...
.迭代器是無限的,所以 itertools.chain(*infinite)
不起作用.
What is a good Python idiom to get an iterator (obviously infinite) that will return each of the elements from the first iterator, then each from the second one, etc. In the example above it would return 1,2,3,1,2,3,...
. The iterator is infinite, so itertools.chain(*infinite)
will not work.
- 扁平化python中的淺表
推薦答案
從 Python 2.6 開始,您可以使用 itertools.chain.from_iterable
:
Starting with Python 2.6, you can use itertools.chain.from_iterable
:
itertools.chain.from_iterable(iterables)
您也可以使用嵌套生成器推導來做到這一點:
You can also do this with a nested generator comprehension:
def flatten(iterables):
return (elem for iterable in iterables for elem in iterable)
這篇關于Python成語鏈接(展平)有限迭代的無限迭代?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!