在 Python 中的迭代器之间交替
- 作者: 吟游诗人
- 来源: 51数据库
- 2022-10-28
问题描述
在 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.
推荐阅读
热点文章
Discord.py(重写)on_member_update 无法正常工作
0
Discord.py 在 vc 中获取用户分钟数
0
discord.py 重写 |为我的命令出错
0
Discord.py rewrite 如何 DM 命令?
0
播放音频时,最后一部分被切断.如何解决这个问题?(discord.py)
0
在消息删除消息 Discord.py
0
如何使 discord.py 机器人私人/直接消息不是作者的人?
0
(Discord.py) 如何获取整个嵌入内容?
0
Discord bot 尽管获得了许可,但不能提及所有人
0
Discord.py discord.NotFound 异常
0
