Double Iteration [duplicate]

2019-03-04 18:49发布

问题:

Possible Duplicate:
How to iterate over two lists - python

I want to iterate over two items at the same time, an iteration that in my mind looks like this:

for elem1 in list 1 and for elem2 in list2:
    do something to elem1; do something to elem2

This syntax, however, is not acceptable. To be clear, I'm not talking about nested for loops, because then I'd be iterating over an entire list for every element in the first list. I want to iterate over the two lists (or whatever) in tandem. Is there a pythonic way to do this?

回答1:

Use zip():

for elem1, elem2 in zip(list1, list2):

If one of these lists is longer than the other, you won't see the elements beyond the length of the shorter list.

On python 2, zip() results in a copy of both lists zipped together, and for large lists that can be a memory burden. Use itertools.izip() for such larger lists, it returns an iterator instead. On python 3, zip() itself already returns an iterator.

If you need to loop over the longest list instead (and fill in a filler value for the missing shorter list elements), use itertools.izip_longest() instead:

from itertools import izip_longest

for elem1, elem2 in izip_longest(list1, list2):