给定一个集合
{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}]
要生成给定集合的所有子集{0, 1, 2, 3},可以使用itertoolsPython 中的模块,该模块提供了一个方便的函数,称为combinations生成指定长度的组合。以下是实现此目的的方法:
itertools
combinations
from itertools import chain, combinations # Original set original_set = {0, 1, 2, 3} # Generate all subsets subsets = chain.from_iterable(combinations(original_set, r) for r in range(len(original_set)+1)) # Convert subsets from tuples to sets subsets = [set(subset) for subset in subsets] # Print the subsets print(subsets)
chain
combinations(original_set, r)
original_set
r
for r in range(len(original_set)+1)
0
len(original_set)
将每个元组转换为一个集合
subsets
运行上述代码将产生以下输出,该输出与您提供的子集相匹配