python - 在 python 3.x 中创建给定列表的所有子集的列表

标签 python list python-3.x

如何在 python 3.x 中创建给定列表的所有子集的列表? 给出的列表像 [1,2,3] 我想要一个像

的输出
[[1],[2],[3],[1,2],[2,3],[1,3],[1,2,3],[]]

最佳答案

您可以使用 itertools.combinations获得组合:

>>> import itertools
>>> xs = [1, 2, 3]

>>> itertools.combinations(xs, 2)  # returns an iterator
<itertools.combinations object at 0x7f88f838ff48>
>>> list(itertools.combinations(xs, 2))  # yields 2-length subsequences
[(1, 2), (1, 3), (2, 3)]


>>> for i in range(0, len(xs) + 1):  # to get all lengths: 0 to 3
...     for subset in itertools.combinations(xs, i):
...         print(list(subset))
... 
[]
[1]
[2]
[3]
[1, 2]
[1, 3]
[2, 3]
[1, 2, 3]

结合列表理解,你会得到你想要的:

>>> [list(subset) for i in range(0, len(xs) + 1)
                  for subset in itertools.combinations(xs, i)]
[[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]

关于python - 在 python 3.x 中创建给定列表的所有子集的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43014681/

相关文章:

python - Cython 用 Visual Studio(Windoes SDK 包)编译 cl.exe 创建.pyd

python - 如何使用 2 个拆分参数拆分字符串?

java - 如何在 Java 中从 List<Double> 转换为 double[]?

python-3.x - 值错误 : arrays must all be same length in python using pandas DataFrame

python - 在 Python 3.5 中运行 PyGMO

python - XOR 加密在*大部分*时间都有效

python - 如何比较python中的两个列表?

list - 获取两个列表元素的所有可能组合的元组列表的 Pythonic 方法是什么?

python - 无法在python中找到质数代码中的错误

python - 无法在 Intellij IDEA 中从 requirements.txt 安装某些库