假设我生成一个卡住集
A = frozenset(frozenset([element]) for element in [1,2,3])
我有空集
E = frozenset(frozenset())
现在我想要两个集合的并集:
U = A | E
这给了我
frozenset({frozenset({2}), frozenset({3}), frozenset({1})})
这假设包含空 frozenset 的 frozenset 本身是空的。不过,我想要
frozenset({frozenset({}), frozenset({2}), frozenset({3}), frozenset({1})})
因此,我想将空集显式添加到集合中。例如,在构建幂集时,我认为这是必要的?
那么:只包含空集的集合族本身是空的吗?在 Python 中,有没有一种方法可以使用变量类型 set
和 frozenset
将空集显式包含到集合族中?
最佳答案
E
是一个空集,没有元素:
>>> frozenset(frozenset())
frozenset()
那是因为 fronenset()
的参数是一个可迭代的要添加的值。 frozenset()
是一个空的可迭代对象,因此不会添加任何内容。
如果您希望E
是一个只有一个元素的集合,您需要传入一个只有一个元素的iterable;使用 {...}
集合符号,或单个元素元组 (...,)
,或列表 [...]
:
>>> frozenset({frozenset()}) # pass in a set() with one element.
frozenset({frozenset()})
现在您得到了预期的输出:
>>> A = frozenset(frozenset([element]) for element in [1,2,3])
>>> E = frozenset({frozenset()})
>>> A | E
frozenset({frozenset({3}), frozenset({2}), frozenset({1}), frozenset()})
关于python - 将空集添加到 python 中的 frozenset 中的一组集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50389974/