Python double iteration

后端 未结 3 1035
忘了有多久
忘了有多久 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:37

    I vote for using zip. The manual suggests "To loop over two or more sequences at the same time, the entries can be paired with the zip() function"

    For example,

    list_one = ['nachos', 'sandwich', 'name']
    list_two = ['nachos', 'sandwich', 'the game']
    for one, two in zip(list_one, list_two):
       if one != two:
          print "Difference found"
    
    0 讨论(0)
  • 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.
    
    0 讨论(0)
  • 2020-12-10 13:00

    In Python 2, you should import itertools and use its izip:

    with open(file1) as f1:
      with open(file2) as f2:
        for line1, line2 in itertools.izip(f1, f2):
          if line1 != line2:
            print 'files are different'
            break
    

    with the built-in zip, both files will be entirely read into memory at once at the start of the loop, which may not be what you want. In Python 3, the built-in zip works like itertools.izip does in Python 2 -- incrementally.

    0 讨论(0)
提交回复
热议问题