同时枚举两个python列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16326853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Enumerate two python lists simultaneously?
提问by Quant Metropolis
How do I enumerate two lists of equal length simultaneously? I am sure there must be a more pythonic way to do the following:
如何同时枚举两个等长的列表?我确信必须有一种更 Pythonic 的方式来执行以下操作:
for index, value1 in enumerate(data1):
print index, value1 + data2[index]
I want to use the index and data1[index] and data2[index] inside the for loop.
我想在 for 循环中使用 index 和 data1[index] 和 data2[index]。
采纳答案by Ashwini Chaudhary
For Python 2:
Use zip:
对于 Python 2:
使用zip:
for index, (value1, value2) in enumerate(zip(data1, data2)):
print index, value1 + value2
Note that zipruns only up to the shorter of the two lists(not a problem for equal length lists), but, in case of unequal length lists if you want to traverse whole list then use itertools.izip_longest.
请注意,zip仅运行到两个列表中较短的一个(对于等长列表来说不是问题),但是,如果您想遍历整个列表,则在长度不等的列表的情况下,请使用itertools.izip_longest.
For Python 3:
Use zip:
对于 Python 3:
使用zip:
for index, (value1, value2) in enumerate(zip(data1, data2)):
print(index, value1 + value2)
Note that zipruns only up to the shorter of the two lists(not a problem for equal length lists), but, in case of unequal length lists if you want to traverse whole list then use itertools.izip_longest.
请注意,zip仅运行到两个列表中较短的一个(对于等长列表来说不是问题),但是,如果您想遍历整个列表,则在长度不等的列表的情况下,请使用itertools.izip_longest.
回答by ddzialak
Suppose you want to use zip:
假设你想使用zip:
>>> for x in zip([1,2], [3,4]):
... print x
...
(1, 3)
(2, 4)
回答by Fred Foo
for i, (x, y) in enumerate(zip(data1, data2)):
In Python 2.x, you might want to use itertools.izipinstead of zip, esp. for very long lists.
在 Python 2.x 中,您可能希望使用, espitertools.izip代替zip。对于很长的列表。
回答by kiriloff
Althought this is not very clear what you look for,
虽然这不是很清楚你要找什么,
>>> data1 = [3,4,5,7]
>>> data2 = [4,6,8,9]
>>> for index, value in enumerate(zip(data1, data2)):
print index, value[0]+value[1]
0 7
1 10
2 13
3 16
回答by Marco Sulla
from itertools import count
for index, value1, value2 in zip(count(), data1, data2):
print(index, value1, value2)
Source: http://www.saltycrane.com/blog/2008/04/how-to-use-pythons-enumerate-and-zip-to/#c2603
来源:http: //www.saltycrane.com/blog/2008/04/how-to-use-pythons-enumerate-and-zip-to/#c2603
回答by SuperNova
Since it has been mentioned that the length are equal,
既然已经提到长度相等,
for l in range(0, len(a)):
print a[l], b[l]

