如何在Python中扩展/连接两个迭代器 [英] How to extend/concatenate two iterators in Python

查看:572
本文介绍了如何在Python中扩展/连接两个迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望以有效的方式连接两个迭代器。

I want concatenate two iterators in an efficient way.

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

Suppose we have two iterators (in Python3)

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

如果我们将它们转换为列表,很容易连接如

If we convert them to lists, it is easy to concatenate like

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

然而,这可能效率不高。

However, this can be not efficient.

我想做类似的事情

y_iter = l1 + l2  # this does not work

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

What is the good way to do this in Python3?

推荐答案

使用 itertools.chain

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

它产生 l1 中的所有物品,以及来自 l2 。有效地连接所产生项目的顺序。在这个过程中它消耗两者。

It yields all the items from l1 and them all the items from l2. Effectively concatenating the sequence of yielded items. In the process it consumes both.

这篇关于如何在Python中扩展/连接两个迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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