我目前在Python的土地上。这就是我需要做的。我已经查看了itertools库,但它似乎只做了排列。
我想要一个输入列表,比如['yahoo','wikipedia','freebase'],并生成一个项目与零个或多个其他项目的每个独特组合......
['yahoo', 'wikipedia', 'freebase']
['yahoo', 'wikipedia']
['yahoo', 'freebase']
['wikipedia', 'freebase']
['yahoo']
['freebase']
['wikipedia']
一些笔记。顺序无关紧要,我正在尝试设计方法来获取任何大小的列表。另外,这种组合有名称吗?
感谢您的帮助!
答案 0 :(得分:3)
>>> l = ['yahoo', 'wikipedia', 'freebase']
>>> import itertools
>>> for i in range(1, len(l) +1):
print(list(itertools.combinations(l, r=i)))
[('yahoo',), ('wikipedia',), ('freebase',)]
[('yahoo', 'wikipedia'), ('yahoo', 'freebase'), ('wikipedia', 'freebase')]
[('yahoo', 'wikipedia', 'freebase')]
P.S。为什么这个维基?
答案 1 :(得分:3)
它被称为powerset。这是itertools docs:
的实现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))
答案 2 :(得分:0)
这称为动力装置。只需按照algorithm进行操作即可。这是一个简单的实现:
def powerset(seq):
if len(seq):
head = powerset(seq[:-1])
return head + [item + [seq[-1]] for item in head]
else:
return [[]]
>>> powerset(['yahoo', 'wikipedia', 'freebase'])
[[], ['yahoo'], ['wikipedia'], ['yahoo', 'wikipedia'], ['freebase'], ['yahoo', 'freebase'], ['wikipedia', 'freebase'], ['yahoo', 'wikipedia', 'freebase']]
另一个:
def powerset(s):
sets = []
indicator = lambda x: x & 1
for element in xrange(2**len(s)):
n = element
subset = []
for x in s:
if indicator(n):
subset.append(x)
n >>= 1
sets.append(subset)
return sets
答案 3 :(得分:0)
你基本上在二进制中从1到2 n -1 计数:
0 0 1 ['freebase']
0 1 0 ['wikipedia']
0 1 1 ['wikipedia', 'freebase']
1 0 0 ['yahoo']
1 0 1 ['yahoo', 'freebase']
1 1 0 ['yahoo', 'wikipedia']
1 1 1 ['yahoo', 'wikipedia', 'freebase']