2016-09-12 7 views
1

以下のa、b、cなどのグループデータがあります。私がしたいのは、データからすべての可能な組み合わせを計算することです。入力データの数が常に同じであれば問題ありません。しかし、私の場合は、入力データの数が0からNまでであると仮定したいと思います。Pythonのdiffernt配列からすべての可能な組み合わせを計算してください。

私は繰り返しループを使わなければならないと思います。しかし、私はこの問題を解決するために反復ループを使用するかどうかはわかりません。

入力

a = ["x", "y"] 
b = ["q", "w", "c"] 
c = ["i", "o", "p"] 
... 

出力リレー

期待される出力は、各値の全ての組み合わせとすべての組み合わせです。私はあなたが探しているものを理解していた場合

[{a:[], b:["q"], c:["i", "o"]}, {a:["x"], b:[], c:["o"]}, ...] 
+3

はあなたの出力はそれほど明確ではありません。より多くの例を提供してください。 –

答えて

5

、あなたが入力のpowersetsitertools.product()を使用することができます(ドキュメントでpowerset()のレシピがあります)。 map()関数を使用して、それぞれの入力にpowersetを適用できます。ここで

from itertools import product, combinations, chain 
from pprint import pprint 

def powerset(iterable): 
    "powerset([1,2,3]) -->() (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" 
    s = list(iterable) 
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) 

names = ['a', 'b', 'c'] 
a = ["x", "y"] 
b = ["q", "w", "c"] 
c = ["i", "o", "p"] 

result = [] 
for values in product(*map(powerset, [a, b, c])): 
    result.append(dict(zip(names, values))) 
pprint(result) 

それがどのように動作するかです:

まず、それはpowersetsを構築します。

>>> list(powerset(["x", "y"])) 
[(), ('x',), ('y',), ('x', 'y')] 
>>> 
>>> list(powerset(["x", "y"])) 
[(), ('x',), ('y',), ('x', 'y')] 
>>> list(powerset(["q", "w", "c"])) 
[(), ('q',), ('w',), ('c',), ('q', 'w'), ('q', 'c'), 
('w', 'c'), ('q', 'w', 'c')] 
>>> list(powerset(["i", "o", "p"])) 
[(), ('i',), ('o',), ('p',), ('i', 'o'), ('i', 'p'), 
('o', 'p'), ('i', 'o', 'p')] 

product()は、各Powersetの1つの要素を引っ張る:

最後
>>> for values in product(*map(powerset, [a, b, c])): 
     print(values) 

((),(),()) 
((),(), ('i',)) 
((),(), ('o',)) 
((),(), ('p',)) 
((),(), ('i', 'o')) 
((),(), ('i', 'p')) 
((),(), ('o', 'p')) 
((),(), ('i', 'o', 'p')) 
((), ('q',),()) 
((), ('q',), ('i',)) 
((), ('q',), ('o',)) 
((), ('q',), ('p',)) 
((), ('q',), ('i', 'o')) 
((), ('q',), ('i', 'p')) 
((), ('q',), ('o', 'p')) 
((), ('q',), ('i', 'o', 'p')) 

を、we zip() togeth ER dict()を作るために、変数名と上記の結果:

# What zip does 
>>> list(zip(['a', 'b', 'c'], ((), ('q',), ('i', 'o', 'p')))) 
[('a',()), ('b', ('q',)), ('c', ('i', 'o', 'p'))] 

# What dict does with the zip: 
>>> dict(zip(['a', 'b', 'c'], ((), ('q',), ('i', 'o', 'p')))) 
{'b': ('q',), 'c': ('i', 'o', 'p'), 'a':()} 
+1

あなたは素晴らしいです!あなたのコードを理解するのに少し時間がかかります。しかし、あなたのコードが私のIPythonで正しく動作していることを確認しました。ありがとうございました。 – jef

関連する問題