嵌套循环的pythonic方式检查两个或多个列表中的项目

时间:2013-07-04 09:04:12

标签: python list loops nested

我想检查python中两个列表中的项目,这两个列表再次放在一个大列表中 在我的代码中,combinedList是大列表,row1和row2是子列表。

我需要检查row1和row2中的项目。我在psudo代码中得到了粗略的想法,因为我是python的新手。是否有任何好的代码可以检查他们的项目的两个列表,而不是多次重复同一对?

row1 = [a,b,c,d,....]
row2 = [s,c,e,d,a,..]

combinedList = [row1 ,row2]

for ls in combinedList:
        **for i=0 ; i < length of ls; i++
            for j= i+1 ; j <length of ls; j++
                do something here item at index i an item at index j**

2 个答案:

答案 0 :(得分:0)

使用zip() built-in function配对两个列表的值:

for row1value, row2value in zip(row1, row2):
    # do something with row1value and row2value

如果您想将row1中的每个元素与row2的每个元素组合(两个列表的乘积),请改为使用itertools.product()

from itertools import product

for row1value, row2value in product(row1, row2):
    # do something with row1value and row2value

zip()简单地将生成len(shortest_list)项的列表配对,product()将一个列表中的每个元素与另一个列表中的每个元素配对,生成len(list1)次{{1} item:

len(list2)

答案 1 :(得分:0)

我猜您正在寻找itertools.product

>>> from itertools import product
>>> row1 = ['a', 'b', 'c', 'd']
>>> row2 = ['s', 'c', 'e', 'd', 'a']
>>> seen = set()             #keep a track of already visited pairs in this set
>>> for x,y in product(row1, row2):
        if (x,y) not in seen and (y,x) not in seen:
            print x,y
            seen.add((x,y))
            seen.add((y,x))
...         
a s
a c
a e
a d
a a
b s
b c
b e
b d
b a
c s
c c
c e
c d
d s

<强>更新

>>> from itertools import combinations
>>> for x,y in combinations(row1, 2):
...     print x,y
...     
a b
a c
a d
b c
b d
c d
相关问题