针对两个或多个li检查项的嵌套循环的python方法

2024-04-29 13:39:43 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我需要检查第1行和第2行中的项目。不过,我对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**

Tags: of项目代码列表forindexitemlength
2条回答

我猜你在找^{}

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

更新:

^{pr2}$

使用^{} built-in function将两个列表的值配对:

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

如果要将row1中的每个元素与row2的每个元素(这两个列表的乘积)组合起来,请改用^{}

^{pr2}$

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

相关问题 更多 >