我该如何同时枚举两个等长的列表? 我相信一定有更pythonic的方法来完成以下操作:
for index, value1 in enumerate(data1):
print index, value1 + data2[index]
我想在for循环中使用索引、data1[index]和data2[index]。在Python 2和Python 3中都可以使用zip
函数:
for index, (value1, value2) in enumerate(zip(data1, data2)):
print(index, value1 + value2) # for Python 2 use: `print index, value1 + value2` (no braces)
请注意,zip
仅运行到两个列表中较短的一个(对于长度相等的列表不是问题),但是,如果你想遍历整个列表,并且列表长度不相等,则可以使用itertools.izip_longest
。
for i, (x, y) in enumerate(zip(data1, data2)):
在Python 2.x中,当你处理非常长的列表时,你可能会想要使用itertools.izip
代替zip
。enumerate
这个单词太长了吗? - Steven Rumbalskienu
;) - Fred Foozip
和 map
很搭!应该提出 Python 4 的请求 ;) ;) - jamylakrange
→ rng
,以便更有力地证明。哦,还有 rpr
。 - Fred Foofrom itertools import count
for index, value1, value2 in zip(count(), data1, data2):
print(index, value1, value2)
来源:http://www.saltycrane.com/blog/2008/04/how-to-use-pythons-enumerate-and-zip-to/#c2603
>>> 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
既然已经提到长度相等,
for l in range(0, len(a)):
print a[l], b[l]
zip
: >>> for x in zip([1,2], [3,4]):
... print x
...
(1, 3)
(2, 4)
zip(data1, data2).index(val1, val2)
。 - Chebhou