python - 如何获取集合的所有子集? (动力装置)

标签 python set powerset

给定一个集合

{0, 1, 2, 3}

如何生成子集:

[set(),
 {0},
 {1},
 {2},
 {3},
 {0, 1},
 {0, 2},
 {0, 3},
 {1, 2},
 {1, 3},
 {2, 3},
 {0, 1, 2},
 {0, 1, 3},
 {0, 2, 3},
 {1, 2, 3},
 {0, 1, 2, 3}]

最佳答案

python itertools page正好有一个 powerset 配方:

from itertools import chain, combinations

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

输出:

>>> list(powerset("abcd"))
[(), ('a',), ('b',), ('c',), ('d',), ('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd'), ('a', 'b', 'c'), ('a', 'b', 'd'), ('a', 'c', 'd'), ('b', 'c', 'd'), ('a', 'b', 'c', 'd')]

如果你不喜欢开头那个空元组,你可以把 range 语句改为 range(1, len(s)+1) 到避免 0 长度的组合。

关于python - 如何获取集合的所有子集? (动力装置),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1482308/

相关文章:

python - 如何在 python 中提取同一类中的多个链接?

python - 使用 =HYPERLINK 和 XlsxWriter 换行文本

python - key 检查时 "key in dict"和 "dict.get(key)"之间的区别

algorithm - 如何生成给定集合的幂集?

python - Python中Powerset的时间复杂度

python - 可逆哈希函数?

java - 从Java中的数组/集合的每个元素中剥离字符

java - 获取对 Set 中重复项的引用

C++ 从文本文件中读取字典并将其存储在排序容器中的最佳方法是什么

c++ - 使用二进制计数对数组的所有子集进行计数