2016-10-18 13 views
0

私は以下のコードを試してみましたが、これを行う有効な方法はありますか?リストと他のリストのアイテムとのPythonの組み合わせ

c = [] 
l = [['A1','A2'], ['B1','B2'], ['C1','C2'] ] 

for i in range(0, len(l) - 1): 
    for j in range(i+1, len(l)): 
     c.append(sorted([l[i][0],l[i][1],l[j][0]])) 
     c.append(sorted([l[i][0],l[i][1],l[j][1]])) 
     c.append(sorted([l[i][0],l[j][0],l[j][1]])) 
     c.append(sorted([l[i][1],l[j][0],l[j][1]])) 

print(c) 

アウト置く:

[['A1', 'A2', 'B1'], ['A1', 'A2', 'B2'], ['A1', 'B1', 'B2'], 
['A2', 'B1', 'B2'], ['A1', 'A2', 'C1'], ['A1', 'A2', 'C2'], 
['A1', 'C1', 'C2'], ['A2', 'C1', 'C2'], ['B1', 'B2', 'C1'], 
['B1', 'B2', 'C2'], ['B1', 'C1', 'C2'], ['B2', 'C1', 'C2'] 
+0

を、 'A2'、 'B1'、 'B2'、 'C​​1'、 'C​​2']、3)) ' – poke

+0

@pokeは別のresを生成しませんウルトラ? – vaultah

+0

@vaultahあなたはそうです。そして今私は混乱している。それなら私を気にしないでください。 – poke

答えて

1

または1つのラインで

from itertools import product 

c = [[k] + i for i, j in product(l, l) if j!=i for k in j] 
2

はこのお試しください: `リスト(itertools.combinations([ 'A1' を試してみてください

# group every 2 lists in list l 
ll = list(itertools.combinations(l, 2)) 

# generate all combinations of 3 elements out from each 2 lists 
c = [list(itertools.combinations(a + b, 3)) for (a, b) in ll] 

# concate all elements 
c = sum(c, []) 
+0

'list(map(list、c))' 'list'オブジェクトのうちのOPの出力として出力します。 –

+0

OPは効率について質問するので、 'c = sum(c、[])'は理想的ではないでしょう( 'O(n^2)')。入れ子にされた理解はより演繹的です: 'c = [x in l for c for x for l]'。 (http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python) – schwobaseggl

関連する問題