python - 如何在 Python 中扩展/连接两个迭代器

标签 python list python-3.x iterator

<分区>

我想以一种高效的方式连接两个迭代器。

假设我们有两个迭代器(在 Python3 中)

l1 = range(10)      # iterator over 0, 1, ..., 9
l2 = range(10, 20)  # iterator over 10, 11, ..., 19

如果我们将它们转换成列表,就很容易拼接起来

y = list(l1) + list(l2)  # 0, 1, ,..., 19

但是,这可能效率不高。

我想做这样的事

y_iter = l1 + l2  # this does not work

在 Python3 中执行此操作的好方法是什么?

最佳答案

使用itertools.chain :

from itertools import chain
y_iter = chain(l1, l2)

它生成 l1 中的所有项目,然后生成 l2 中的所有项目。有效地连接产生的项目的序列。在此过程中,它同时消耗了两者。

关于python - 如何在 Python 中扩展/连接两个迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44116557/

相关文章:

python - Sqlite从数据库中操作字符串

python - 收集所有不同轮廓的非零像素

java - 如何使用集合的 addall() 方法?

list - 在 Dart 中更改列表大小的最佳方法是什么?

Python3 和 ASCII

python - python中的矩阵匹配

python - 当文件路径输入不可见时在 selenium python 中上传照片

Python popen 命令。等待命令完成

list - 如何删除列表中的第一个元素

python-3.x - Pyinstaller 可执行文件失败并出现 pkg_resources.DistributionNotFound 错误