Python idiom to chain (flatten) an infinite iterable of finite iterables?(Python成语链接(展平)有限迭代的无限迭代?)
问题描述
假设我们有一个返回列表(或有限迭代器)的迭代器(无限迭代器),例如由
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成语链接(展平)有限迭代的无限迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python成语链接(展平)有限迭代的无限迭代?


- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- python-m http.server 443--使用SSL? 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12
- 沿轴计算直方图 2022-01-01
- padding='same' 转换为 PyTorch padding=# 2022-01-01