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 中的迭代器之间交替
基础教程推荐
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
