0

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

我需要检查 row1 和 row2 中的项目。但是,由于我是 python 新手,所以我对 psudo 代码有了大致的了解。是否有任何好的代码可以检查他们的项目的两个列表而不重复同一对多次?

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**
4

2 回答 2

1

我猜你正在寻找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
于 2013-07-04T09:07:30.603 回答
0

使用zip()内置函数对两个列表的值进行配对:

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)时间len(list2)项目:

>>> row1 = [1, 2, 3]
>>> row2 = [9, 8, 7]
>>> for a, b in zip(row1, row2):
...     print a, b
... 
1 9
2 8
3 7
>>> from itertools import product
>>> for a, b in product(row1, row2):
...     print a, b
... 
1 9
1 8
1 7
2 9
2 8
2 7
3 9
3 8
3 7
于 2013-07-04T09:06:06.510 回答