2017-03-08 13 views
0

同じサイズのリストが2つあります。 list1PythonリストItertoolsとForループ

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

startnlist2endnに相当します。

さらなる計算のために、両方のリストを単一のforループで使用したいと思います。 問題:ループのforの各リストから2つの要素の組み合わせを使用したいとします。例: start1,をlist1およびend1,end3からlist2に抽出し、これらの4つの値をループに使用したいとします。for

単一のリストについては

、2つの要素の組み合わせを抽出するために、私はそれが次のコードを知っている:

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

しかし、どのように私はlist2から2つのlist1からの値と同じ対応する値を抽出し、中に使用するのですかforループ?

答えて

4

次の2つのリストを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] 

編集:第二の考えで、これはPythonの方法です。私は他の人が同じ考えを持っているのを見る。そして、その組み合わせを行う(S1、E1)、(S2、E2)、など:タプルの束の中に一緒に開始と終了のリストを結合する

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

使用zip

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