在 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 中的迭代器之间交替的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
使用 python 解析非常大的 xml 文件时出现问题Troubles while parsing with python very large xml file(使用 python 解析非常大的 xml 文件时出现问题)
使用 Python 2 在 XML 中按属性查找所有节点Find all nodes by attribute in XML using Python 2(使用 Python 2 在 XML 中按属性查找所有节点)
Python - 如何解析 xml 响应并将元素值存储在变量中Python - How to parse xml response and store a elements value in a variable?(Python - 如何解析 xml 响应并将元素值存储在变量中?)
如何在 Python 中获取 XML 标记值How to get XML tag value in Python(如何在 Python 中获取 XML 标记值)
如何使用 ElementTree 正确解析 utf-8 xml?How to correctly parse utf-8 xml with ElementTree?(如何使用 ElementTree 正确解析 utf-8 xml?)
将 XML 从 URL 解析为 python 对象Parse XML from URL into python object(将 XML 从 URL 解析为 python 对象)