问题
Suppose I generate a frozenset with
A = frozenset(frozenset([element]) for element in [1,2,3])
And I have the empty set
E = frozenset(frozenset())
Now I want to have the union of both sets:
U = A | E
This gives me
frozenset({frozenset({2}), frozenset({3}), frozenset({1})})
this assumes, that a frozenset, containing an empty frozenset is itself empty. However, I'd like to have
frozenset({frozenset({}), frozenset({2}), frozenset({3}), frozenset({1})})
So, I'd like to add the empty set explicitly to the set. This is, for example, necessary in my opinion when constructing a power set?
So: Is a family of sets that only contains the empty set itself empty? Is there a way, in Python, to explicitly include an empty set into a family of sets using the variable types set
and frozenset
?
回答1:
E
is an empty set, with no elements:
>>> frozenset(frozenset())
frozenset()
That's because the argument to fronenset()
is an iterable of values to add. frozenset()
is an empty iterable, so nothing is added.
If you expected E
to be a set with one element, you need to pass in an iterable with one element; use {...}
set notation, or a single element tuple (...,)
, or a list [...]
:
>>> frozenset({frozenset()}) # pass in a set() with one element.
frozenset({frozenset()})
Now you get your expected output:
>>> A = frozenset(frozenset([element]) for element in [1,2,3])
>>> E = frozenset({frozenset()})
>>> A | E
frozenset({frozenset({3}), frozenset({2}), frozenset({1}), frozenset()})
来源:https://stackoverflow.com/questions/50389974/add-the-empty-set-to-a-family-of-sets-in-a-frozenset-in-python