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匹配Stata加权xtil命令的确定方法? 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01