2012-04-28 42 views
7

說我有個原子的一個這樣的數組:創建的組原子的列表

['a', 'b', 'c'] 

(長度可以是任何)

我想創建的集合,可以是一個列表與他們做:

[ 
    ['a'], ['b'], ['c'], 
    ['a', 'b'], ['a', 'c'], ['b', 'c'], 
    ['a', 'b', 'c'] 
] 

是否有可能很容易在python中做到這一點?

也許這很容易做,但我自己並沒有得到它。
謝謝。

+0

你錯過了'[ 'B', 'C']',順便說一下。 ;) – 2012-04-28 22:08:15

+0

@ Li-aungYip真的,修好:)謝謝。 – Nuno 2012-04-28 22:09:14

回答

15

這聽起來好像powerset

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)) 
+0

如果你從'1'開始,失去空元組 – jamylak 2012-04-28 22:08:17

+1

釘住它。拿我的upvotes。 ('itertools':有*任何*它不能做的?) – 2012-04-28 22:08:37

+0

完美!你讓我今天一整天都感覺很好!! :) 非常感謝你! – Nuno 2012-04-28 22:23:47

4

容易。使用itertools.combinations()

from itertools import combinations 

atom = list('abc') 

combs = [i for j in range(1, len(atom) + 1) for i in combinations(atom, j)] 

這將產生:

[('a',), ('b',), ('c',), ('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b', 'c')] 
0

你也可以這樣做:

from itertools import product 
masks = [p for p in product([0, 1], repeat=len(data))] 
combs = [[x for i, x in enumerate(data) if mask[i]] for mask in masks]