2013-07-10 50 views
-1

我有6名名單,也就是說,如何使用組合

a=[1,1,0,0] 
b=[0,1,1,0] 
c=[0,0,1,1] 
d .... until f. 

我要生成總和的結果從2所列出開始,直到6所列出清單的所有可能的組合。例如,我想計算a + b,a + c,.. a + f的結果。然後,a + b + c,a + b + d ......等。我知道鋤頭計算兩個或三個列表的結果,但我堅持如何生成列表的組合。我試圖定義列表的列表,然後使用組合,帶參數2生成所有可能的組合,2 3名列表(爲例)如下:

import itertools 

alphabet = [[0,0,0],[0,0,1],[0,1,0]] 

combos = itertools.combinations(alphabet, 2) 

usable_combos = [] 
for e in combos: 
    usable_combos.append(e) 

但這根本不會產生任何東西。當我打印usable_combos,我得到:

[[0,0,0],[0,0,1],[0,1,0]] 

我的問題是:使用的組合,我怎麼能生產的6套不同的我有所有可能的組合(2至6種組合)?

+3

的源代碼拷貝粘貼產生一組3種組合。你確定你打印的是正確的變量嗎? – Mikhail

+1

作爲一個方面說明:你最後得到的循環完全等同於'usable_combos = list(combos)',除了更慢和更難以閱讀。 – abarnert

+1

輸出不是'[[0,0,0],[0,0,1],[0,1,0]]',它是'[([0,0,0],[0,0, 1]),([0,0,0],[0,1,0]),([0,0,1],[0,1,0])]]。這正是我所期望的。如果你期望有所不同,請告訴我們你的期望,並告訴你如何得到它。 – abarnert

回答

2

使用range(1, len(lis)+1)可獲得傳遞給combinations的第二個參數(r)的值。或者range(2, len(lis)+1)如果你想開始從2

>>> from itertools import combinations 
>>> lis = [[0,0,0],[0,0,1],[0,1,0]] 
>>> for i in range(1, len(lis)+1): 
...  for c in combinations(lis,i): 
...   print c 
...   
([0, 0, 0],) 
([0, 0, 1],) 
([0, 1, 0],) 
([0, 0, 0], [0, 0, 1]) 
([0, 0, 0], [0, 1, 0]) 
([0, 0, 1], [0, 1, 0]) 
([0, 0, 0], [0, 0, 1], [0, 1, 0]) 

正如指出的評論可能@abarnert,可能是你想要的:

>>> from pprint import pprint 
>>> from itertools import chain 
>>> flatten = chain.from_iterable 
>>> ans = [list(flatten(c)) for i in range(2, len(lis)+1) for c in permutations(lis,i)] 
>>> pprint(ans) 
[[0, 0, 0, 0, 0, 1], 
[0, 0, 0, 0, 1, 0], 
[0, 0, 1, 0, 0, 0], 
[0, 0, 1, 0, 1, 0], 
[0, 1, 0, 0, 0, 0], 
[0, 1, 0, 0, 0, 1], 
[0, 0, 0, 0, 0, 1, 0, 1, 0], 
[0, 0, 0, 0, 1, 0, 0, 0, 1], 
[0, 0, 1, 0, 0, 0, 0, 1, 0], 
[0, 0, 1, 0, 1, 0, 0, 0, 0], 
[0, 1, 0, 0, 0, 0, 0, 0, 1], 
[0, 1, 0, 0, 0, 1, 0, 0, 0]] 
+1

從第一段我可以看出,他不想要這個,他希望'[0,0,0] + [0,0,1]',然後'[0,0,0] + [0 ,1,0]',然後'[0,0,0] + [0,0,1] + [0,1,0]',然後'[0,0,1] + [0,1,0 ]',但不是原來的個人名單。這是...不是組合,我不確定它是什麼。所以我不認爲這回答他的問題,但我不知道他的問題是否可以在沒有澄清的情況下回答... – abarnert

+0

也許他希望'[flatten(c)for i in range(2,len(lis)+1)for c在組合(lis,1)]'(其中'flatten = itertools.chain.from_iterable')? – abarnert

+0

@abarnert可能是他想要這個,我已經更新了我的答案,添加了「flatten」版本。 –