Python double iteration

后端 未结 3 1047
忘了有多久
忘了有多久 2020-12-10 12:12

What is the pythonic way of iterating simultaneously over two lists?

Suppose I want to compare two files line by line (compare each ith line in one file

3条回答
  •  死守一世寂寞
    2020-12-10 12:39

    In lockstep (for Python ≥3):

    for line1, line2 in zip(file1, file2):
       # etc.
    

    As a "2D array":

    for line1 in file1:
       for line2 in file2:
         # etc.
       # you may need to rewind file2 to the beginning.
    

提交回复
热议问题