给定 Python 中的项目列表,我如何获得项目的所有可能组合?
这个网站上有几个类似的问题,建议使用 itertools.combinations
,但只返回我需要的子集:
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)
如你所见,它只返回严格顺序的项目,不返回 (2, 1)
, (3, 2)
, (3, 1)
, (2, 1, 3)
, (3, 1, 2)
, (2, 3, 1)
和 (3, 2, 1)
。有什么解决方法吗?我好像什么都想不出来。
最佳答案
>>> 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)
....
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)
关于python - 生成列表的所有可能组合, "itertools.combinations"遗漏了一些结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17434070/