python - 生成列表的所有可能组合, "itertools.combinations"遗漏了一些结果

标签 python list combinations

给定 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)。有什么解决方法吗?我好像什么都想不出来。

最佳答案

使用 itertools.permutations:

>>> 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/

相关文章:

python - Django 休息框架 : testing update action doesn't return 400 if request data is invalid

python - 使用 SMTP 和 Python 3 发送 xlsx 文件

java - 比双重嵌套的 ArrayList 更有效?

java - 查找尚未使用的最简单整数组合的算法

python - 在递归函数中使用python数组会导致引用丢失

arrays - Python-组合2个具有相同尺寸的掩码数组

python - TensorFlow 数据集的意外维度

python - 带有负索引的 str.format(list) 在 Python 中不起作用

java - 使用 List Stream 过滤器与 for 循环

python - 按长度排序字符串列表不起作用