7

Is there a clever way to iterate over two lists in Python (without using list comprehension)?

I mean, something like this:

# (a, b) is the cartesian product between the two lists' elements
for a, b in list1, list2:
   foo(a, b)

instead of:

for a in list1:
    for b in list2:
        foo(a, b)
4

3 回答 3

13

itertools.product() does exactly this:

for a, b in itertools.product(list1, list2):
  foo(a, b)

It can handle an arbitrary number of iterables, and in that sense is more general than nested for loops.

于 2012-05-02T17:19:11.353 回答
0
for a,b in zip(list1, list2):
    foo(a,b)

zip combines the elements of lists / arrays together element wise into tuples. e.g.

list1 = [1,2,5]
list2 = [-2,8,0]
for i in zip(list1,list2):
    print(i)
>>> (1, -2)
>>> (2, 8)
>>> (5, 0)
于 2018-05-31T09:46:19.477 回答
0

Use zip it allows you to zip two or more lists and iterate at a time.

list= [1, 2]
list2=[3,4]
combined_list = zip(list, list2)
for a in combined_list:
        print(a)
于 2018-05-31T10:03:08.127 回答