2017-03-08 112 views
0

我有2個相同大小的列表。Python列表Itertools和For循環

list1 = [start1,start2,start3, start4] 
list2 = [end1, end2, end3, end4] 

list1startn對應endnlist2

我想在一個for循環中使用這兩個列表來進一步計算。 問題是:我想使用for循環中每個列表中的2個元素的組合。例如: 我想從list1end1,end3中提取start1,start3,list2,並在for循環中使用這4個值。

對於單列表,提取2種元素的組合,我知道這是下面的代碼:

import itertools 
for a, b in itertools.combinations(mylist, 2):  

但是我怎麼提取list1 2個值和相同的對應值從list2和使用一個for循環?

回答

4

可以zip兩個列表,然後使用combination拉出值:

list1 = ['a', 'b', 'c', 'd'] 
list2 = [1,2,3,4] 

from itertools import combinations 
for x1, x2 in combinations(zip(list1, list2), 2): 
    print(x1, x2) 

#(('a', 1), ('b', 2)) 
#(('a', 1), ('c', 3)) 
#(('a', 1), ('d', 4)) 
#(('b', 2), ('c', 3)) 
#(('b', 2), ('d', 4)) 
#(('c', 3), ('d', 4)) 
0

有可能是一個更Python的方式,但試試這個:

from itertools import combinations 

for i, j in combinations(range(4), 2): 
    list1_1, list1_2, list2_1, list2_2 = list1[i], list1[j], list2[i], list2[j] 

編輯:關於第二個想法此是Pythonic的方式。我看到其他人有相同的想法。

for (list1_1, list1_2), (list2_1, list2_2) in combinations(zip(list1, list2), 2): 
0

使用zip到開始和結束清單組合在一起成一束元組:(S1,E1),(S2,E2)等,然後做的那組合:

import itertools 

starts = 'start1 start2 start3 start4'.split() 
ends = 'end1 end2 end3 end4'.split() 

se_pairs = zip(starts, ends) 

for a,b in itertools.combinations(se_pairs, 2): 
    a_start, a_end = a 
    b_start, b_end = b 

    print("a: (", a_start, ",", a_end, ")", "b: (", b_start, ",", b_end, ")")