在python中生成列表的所有组合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17434070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generating all combinations of a list in python
提问by Minas Abovyan
Here's the question:
这是问题:
Given a list of items in Python, how would I go by to get all the possible combinations of the items?
给定 Python 中的项目列表,我将如何获得项目的所有可能组合?
There are several similar questions on this site, that suggest using itertools.combine, but that returns only a subset of what I need:
该站点上有几个类似的问题,建议使用 itertools.combine,但这仅返回我需要的一个子集:
stuff = [1, 2, 3]
for L in range(0, len(stuff)+1):
for subset in itertools.combinations(stuff, L):
print(subset)
()
(1,)
(2,)
(3,)
(1, 2)
(1, 3)
(2, 3)
(1, 2, 3)
As you see, it returns only items in a strict order, not returning (2, 1), (3, 2), (3, 1), (2, 1, 3), (3, 1, 2), (2, 3, 1), and (3, 2, 1). Is there some workaround that? I can't seem to come up with anything.
如你所见,它只返回严格顺序的项,不返回 (2, 1), (3, 2), (3, 1), (2, 1, 3), (3, 1, 2), ( 2, 3, 1) 和 (3, 2, 1)。有什么解决方法吗?我似乎想不出什么。
采纳答案by Ashwini Chaudhary
>>> import itertools
>>> stuff = [1, 2, 3]
>>> for L in range(0, len(stuff)+1):
for subset in itertools.permutations(stuff, L):
print(subset)
...
()
(1,)
(2,)
(3,)
(1, 2)
(1, 3)
(2, 1)
(2, 3)
(3, 1)
....
help on itertools.permutations
:
帮助itertools.permutations
:
permutations(iterable[, r]) --> permutations object
Return successive r-length permutations of elements in the iterable.
permutations(range(3), 2) --> (0,1), (0,2), (1,0), (1,2), (2,0), (2,1)
>>>
回答by Brien
itertools.permutations
is going to be what you want. By mathematical definition, order does not matter for combinations
, meaning (1,2)
is considered identical to (2,1)
. Whereas with permutations
, each distinct ordering counts as a unique permutation, so (1,2)
and (2,1)
are completely different.
itertools.permutations
将是你想要的。根据数学定义,顺序与 无关combinations
,含义(1,2)
被认为与 相同(2,1)
。而对于permutations
,每个不同的排序都算作一个唯一的排列,因此(1,2)
和(2,1)
完全不同。
回答by Sukrit Kalra
Are you looking for itertools.permutations
instead?
From help(itertools.permutations)
,
从help(itertools.permutations)
,
Help on class permutations in module itertools:
class permutations(__builtin__.object)
| permutations(iterable[, r]) --> permutations object
|
| Return successive r-length permutations of elements in the iterable.
|
| permutations(range(3), 2) --> (0,1), (0,2), (1,0), (1,2), (2,0), (2,1)
Sample Code :
示例代码:
>>> from itertools import permutations
>>> stuff = [1, 2, 3]
>>> for i in range(0, len(stuff)+1):
for subset in permutations(stuff, i):
print(subset)
()
(1,)
(2,)
(3,)
(1, 2)
(1, 3)
(2, 1)
(2, 3)
(3, 1)
(3, 2)
(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)
From Wikipedia, the difference between permutations and combinations :
从维基百科,排列和组合之间的区别:
Permutation :
排列:
Informally, a permutation of a set of objects is an arrangement of those objects into a particular order. For example, there are six permutations of the set {1,2,3}, namely (1,2,3), (1,3,2), (2,1,3), (2,3,1), (3,1,2), and (3,2,1).
非正式地,一组对象的排列是将这些对象按特定顺序排列。例如集合{1,2,3}有六种排列,即(1,2,3),(1,3,2),(2,1,3),(2,3,1) , (3,1,2) 和 (3,2,1)。
Combination :
组合 :
In mathematics a combination is a way of selecting several things out of a larger group, where (unlike permutations) order does not matter.
在数学中,组合是从更大的组中选择几个事物的一种方式,其中(与排列不同)顺序无关紧要。
回答by saimadhu.polamuri
You can generate all the combinations of a list in python using this simple code
您可以使用这个简单的代码在 python 中生成列表的所有组合
import itertools
a = [1,2,3,4]
for i in xrange(1,len(a)+1):
print list(itertools.combinations(a,i))
Result:
结果:
[(1,), (2,), (3,), (4,)]
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
[(1, 2, 3, 4)]
回答by Shashank Singh
I assume you want all possible combinations as 'sets' of values. Here is a piece of code that I wrote that might help give you an idea:
我假设您希望将所有可能的组合作为值的“集合”。这是我写的一段代码,可能有助于给你一个想法:
def getAllCombinations(object_list):
uniq_objs = set(object_list)
combinations = []
for obj in uniq_objs:
for i in range(0,len(combinations)):
combinations.append(combinations[i].union([obj]))
combinations.append(set([obj]))
return combinations
Here is a sample:
这是一个示例:
combinations = getAllCombinations([20,10,30])
combinations.sort(key = lambda s: len(s))
print combinations
... [set([10]), set([20]), set([30]), set([10, 20]), set([10, 30]), set([20, 30]), set([10, 20, 30])]
I think this has n! time complexity, so be careful. This works but may not be most efficient
我认为这有n!时间复杂度,所以要小心。这有效但可能不是最有效的
回答by Uri Goren
Here is a solution without itertools
这是一个没有 itertools 的解决方案
First lets define a translation between an indicator vector of 0
and 1
s and a sub-list (1
if the item is in the sublist)
首先让我们定义0
和1
s的指示向量和子列表(1
如果项目在子列表中)之间的转换
def indicators2sublist(indicators,arr):
return [item for item,indicator in zip(arr,indicators) if int(indicator)==1]
Next, Well define a mapping from a number between 0
and 2^n-1
to the its binary vector representation (using string's format
function) :
接着,那么限定从之间的数的映射0
和2^n-1
(使用字符串的到其二进制向量表示format
函数):
def bin(n,sz):
return ('{d:0'+str(sz)+'b}').format(d=n)
All we have left to do, is to iterate all the possible numbers, and call indicators2sublist
我们剩下要做的就是迭代所有可能的数字,然后调用 indicators2sublist
def all_sublists(arr):
sz=len(arr)
for n in xrange(0,2**sz):
b=bin(n,sz)
yield indicators2sublist(b,arr)
回答by Matt Slap
just thought i'd put this out there since i couldn't fine EVERY possible outcome and keeping in mind i only have the rawest most basic of knowledge when it comes to python and there's probably a much more elegant solution...(also excuse the poor variable names
只是想我会把它放在那里,因为我无法确定所有可能的结果,请记住,当涉及到 python 时,我只有最原始的最基本的知识,并且可能有一个更优雅的解决方案......(也请原谅可怜的变量名
testing = [1, 2, 3]
测试 = [1, 2, 3]
testing2= [0]
测试2 = [0]
n = -1
n = -1
def testingSomethingElse(number):
def testingSomethingElse(数字):
try:
testing2[0:len(testing2)] == testing[0]
n = -1
testing2[number] += 1
except IndexError:
testing2.append(testing[0])
while True:
为真:
n += 1
testing2[0] = testing[n]
print(testing2)
if testing2[0] == testing[-1]:
try:
n = -1
testing2[1] += 1
except IndexError:
testing2.append(testing[0])
for i in range(len(testing2)):
if testing2[i] == 4:
testingSomethingElse(i+1)
testing2[i] = testing[0]
i got away with == 4 because i'm working with integers but you may have to modify that accordingly...
我逃脱了 == 4 因为我正在使用整数,但您可能需要相应地修改它...