一次迭代多个列表的最佳方法是什么? [英] What is the best way to iterate over multiple lists at once?
本文介绍了一次迭代多个列表的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有两个或更多长度相同的列表.迭代它们的好方法是什么?
Let's say I have two or more lists of same length. What's a good way to iterate through them?
a
, b
是列表.
for i, ele in enumerate(a):
print ele, b[i]
或
for i in range(len(a)):
print a[i], b[i]
或者我遗漏了什么变体?
or is there any variant I am missing?
使用一种比另一种有什么特别的优势吗?
Is there any particular advantages of using one over other?
推荐答案
通常的方式是使用 zip()
:
The usual way is to use zip()
:
for x, y in zip(a, b):
# x is from a, y is from b
当两个可迭代对象 a
和 b
中较短的一个用完时,这将停止.另外值得注意的是:itertools.izip()
(仅限 Python 2)和 itertools.izip_longest()
(Python 3 中的itertools.zip_longest()
).
This will stop when the shorter of the two iterables a
and b
is exhausted. Also worth noting: itertools.izip()
(Python 2 only) and itertools.izip_longest()
(itertools.zip_longest()
in Python 3).
这篇关于一次迭代多个列表的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文