2013-07-04 66 views
0

我想檢查項目對兩個列表中的Python再次放在一個大列表 在我的代碼中,combinedList是大列表,row1和row2是子列表,名單。pythonic方式嵌套循環檢查項目對兩個或多個列表

我需要檢查對方的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** 

回答

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

一個更多的問題,如果我想比較row1項目如「a和b,a和c,a和d,b和c,b和d,c和d「而不是反向對......謝謝! – Peter

+0

@Peter爲此使用'itertools.combinations'。我已經添加了一個小例子。 –

+0

謝謝@Ashwini – Peter

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