說我有個原子的一個這樣的數組:創建的組原子的列表
['a', 'b', 'c']
(長度可以是任何)
我想創建的集合,可以是一個列表與他們做:
[
['a'], ['b'], ['c'],
['a', 'b'], ['a', 'c'], ['b', 'c'],
['a', 'b', 'c']
]
是否有可能很容易在python中做到這一點?
也許這很容易做,但我自己並沒有得到它。
謝謝。
說我有個原子的一個這樣的數組:創建的組原子的列表
['a', 'b', 'c']
(長度可以是任何)
我想創建的集合,可以是一個列表與他們做:
[
['a'], ['b'], ['c'],
['a', 'b'], ['a', 'c'], ['b', 'c'],
['a', 'b', 'c']
]
是否有可能很容易在python中做到這一點?
也許這很容易做,但我自己並沒有得到它。
謝謝。
這聽起來好像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))
容易。使用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')]
你也可以這樣做:
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]
你錯過了'[ 'B', 'C']',順便說一下。 ;) – 2012-04-28 22:08:15
@ Li-aungYip真的,修好:)謝謝。 – Nuno 2012-04-28 22:09:14