What is the difference between chain and chain.from_iterable in itertools?(itertools中chain和chain.from_iterable有什么区别?)
问题描述
我在互联网上找不到任何有效的例子,我可以看到它们之间的区别以及为什么要选择一个而不是另一个.
I could not find any valid example on the internet where I can see the difference between them and why to choose one over the other.
推荐答案
第一个接受 0 个或多个参数,每个参数是一个可迭代对象,第二个接受一个预期生成可迭代对象的参数:
The first takes 0 or more arguments, each an iterable, the second one takes one argument which is expected to produce the iterables:
from itertools import chain
chain(list1, list2, list3)
iterables = [list1, list2, list3]
chain.from_iterable(iterables)
但 iterables
可以是任何产生可迭代对象的迭代器:
but iterables
can be any iterator that yields the iterables:
def gen_iterables():
for i in range(10):
yield range(i)
itertools.chain.from_iterable(gen_iterables())
使用第二种形式通常是一种方便的情况,但由于它会延迟循环输入可迭代对象,因此它也是链接无限个有限迭代器的唯一方法:
Using the second form is usually a case of convenience, but because it loops over the input iterables lazily, it is also the only way you can chain an infinite number of finite iterators:
def gen_iterables():
while True:
for i in range(5, 10):
yield range(i)
chain.from_iterable(gen_iterables())
上面的例子将给你一个迭代,它产生一个循环的数字模式,它永远不会停止,但永远不会消耗比单个 range()
调用所需更多的内存.
The above example will give you a iterable that yields a cyclic pattern of numbers that will never stop, but will never consume more memory than what a single range()
call requires.
这篇关于itertools中chain和chain.from_iterable有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:itertools中chain和chain.from_iterable有什么区别?


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