Skip to main content
 首页 » 编程设计

python之如何打印字典的所有子集

2025年05月04日13yxwkf

我有一个基本案例要处理,即创建字典并将其子集打印到列表中。

我已经尝试过 itertools、chain 和组合;

 
from itertools import chain, combinations 
 
dict = {1,2,3} 
 
def powerset(iterable): 
    s = set(dict) 
    return chain.from_iterable(combinations(s,r) for r in range(len(s)+1)) 
 
set(powerset("dict")) 

这段代码给出:

{(), (1,), (1, 2), (1, 2, 3), (1, 3), (2,), (2, 3), (3,)} 

我希望这样:

[{}, {1}, {1, 2}, {1, 2, 3}, {1, 3}, {2}, {2, 3}, {3}] 

请您参考如下方法:

首先,您将 dictionaries 混为一谈与 sets .其次,强烈建议不要将您的变量命名为与 python 关键字或方法相同的名称,就像您在此处使用 dict 所做的那样。 现在,itertools 中的所有函数都返回一个以 tuple 为元素的可迭代对象。因此,您需要将它们转换回集合。

[set(subset) for subset in powerset(dict)]