簡體   English   中英

嵌套循環檢查兩個或多個列表項的pythonic方法

[英]pythonic way for nested loops checking items against two or more list

我想對照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**

我猜你在找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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM