Alternating between iterators in Python(在 Python 中的迭代器之间交替)
问题描述
在 Python 中交替从不同迭代器获取值的最有效方法是什么,例如 alternate(xrange(1, 7, 2), xrange(2, 8, 2)) 将产生 1、2、3、4、5、6.我知道实现它的一种方法是:
What is the most efficient way to alternate taking values from different iterators in Python, so that, for example, alternate(xrange(1, 7, 2), xrange(2, 8, 2)) would yield 1, 2, 3, 4, 5, 6. I know one way to implement it would be:
def alternate(*iters):
while True:
for i in iters:
try:
yield i.next()
except StopIteration:
pass
但是有没有更有效或更清洁的方法?(或者,更好的是,我错过了一个 itertools 函数?)
But is there a more efficient or cleaner way? (Or, better yet, an itertools function I missed?)
推荐答案
zip呢?你也可以试试 itertools 的 izip
what about zip? you may also try izip from itertools
>>> zip(xrange(1, 7, 2),xrange(2, 8 , 2))
[(1, 2), (3, 4), (5, 6)]
如果这不是您想要的,请在您的问题帖子中提供更多示例.
if this is not what you want, please give more examples in your question post.
这篇关于在 Python 中的迭代器之间交替的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Python 中的迭代器之间交替
基础教程推荐
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 包装空间模型 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
