Python成语链(flatten)无限可迭代的有限迭代? [英] Python idiom to chain (flatten) an infinite iterable of finite iterables?

查看:250
本文介绍了Python成语链(flatten)无限可迭代的有限迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个返回列表(或有限迭代器)的迭代器(无限一个),例如由

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.

  • Flattening a shallow list in python

推荐答案

从Python 2.6开始,你可以使用< a href =https://docs.python.org/library/itertools.html#itertools.chain.from_iterable =noreferrer> 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成语链(flatten)无限可迭代的有限迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆