Enumerate two python lists simultaneously?

前端 未结 6 793
既然无缘
既然无缘 2020-12-13 03:42

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(         


        
6条回答
  •  死守一世寂寞
    2020-12-13 04:06

    Use zip for both Python2 and Python3:

    for index, (value1, value2) in enumerate(zip(data1, data2)):
        print(index, value1 + value2)  # for Python 2 use: `print index, value1 + value2` (no braces)
    

    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 the whole list then use itertools.izip_longest.

提交回复
热议问题