[英]A Combinations of Items in Given List
I'm currently in Python land. 我目前在Python领域。 This is what I need to do.
这就是我需要做的。 I have already looked into the itertools library but it seems to only do permutations.
我已经研究过itertools库,但它似乎只进行排列。
I want to take an input list, like ['yahoo', 'wikipedia', 'freebase'] and generate every unique combination of one item with zero or more other items... 我想输入一个输入列表,例如['yahoo','wikipedia','freebase'],并生成一个项目与零个或多个其他项目的每个唯一组合...
['yahoo', 'wikipedia', 'freebase']
['yahoo', 'wikipedia']
['yahoo', 'freebase']
['wikipedia', 'freebase']
['yahoo']
['freebase']
['wikipedia']
A few notes. 一些注意事项。 Order does not matter and I am trying to design the method to take a list of any size.
顺序无关紧要,我正在尝试设计该方法以采用任意大小的列表。 Also, is there a name for this kind of combination?
另外,这种组合是否有名称?
Thanks for your help! 谢谢你的帮助!
>>> 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')]
PS why is this wiki? PS为什么这个维基?
It's called a powerset. 这称为电源集。 This is an implementation from the itertools docs :
这是来自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))
That is called a power set. 这就是所谓的功率集。 Just follow this algorithm .
只需遵循此算法即可 。 Here's a simple implementation:
这是一个简单的实现:
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']]
And another: 还有一个:
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
You're basically counting from 1 to 2 n -1 in binary : 您基本上是从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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.