本文介绍了同时枚举两个python列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何同时枚举两个长度相等的列表?我确信必须有一种更Python化的方法来执行以下操作:

How do I enumerate two lists of equal length simultaneously?I am sure there must be a more pythonic way to do the following:

for index, value1 in enumerate(data1):
    print index, value1 + data2[index]

我想在for循环中使用索引以及data1 [index]和data2 [index].

I want to use the index and data1[index] and data2[index] inside the for loop.

推荐答案

对于Python 2:
使用 zip :

For Python 2:
Use zip:

for index, (value1, value2) in enumerate(zip(data1, data2)):
    print index, value1 + value2

请注意,zip最多只能运行两个列表中较短的一个(对于长度相等的列表来说不是问题),但是,如果长度不相等,则要遍历整个列表,请使用 itertools.izip_longest .

Note that zip runs 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.

对于Python 3:
使用 zip :

For Python 3:
Use zip:

for index, (value1, value2) in enumerate(zip(data1, data2)):
    print(index, value1 + value2)

请注意,zip最多只能运行两个列表中较短的一个(对于长度相等的列表来说不是问题),但是,如果长度不相等,则要遍历整个列表,请使用 itertools.izip_longest .

Note that zip runs 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.

这篇关于同时枚举两个python列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 19:00
查看更多