2012-05-02 97 views
6

有没有一种巧妙的方式来迭代两个列表中的Python(不使用列表理解)?Python多列表迭代

我的意思是,像这样的:

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

代替:

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

回答

13

itertools.product()正是这样做的:

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

它可以处理iterables的任意号码,从这个意义上说,它比嵌套的for循环更普遍。