set A set is a variable sequence , The program can change the elements in the sequence ;frozenset A set is an immutable sequence , The program cannot change the elements in the sequence .set All the methods in a set that can change the set itself , such as remove()、discard()、add() etc. ,frozenset Don't support ;set A method in a set that does not change the set itself ,fronzenset All support .
We can enter... In an interactive programming environment dir(frozenset)
Check it out. frozenset Collection support methods :
>>> dir(frozenset)
['copy', 'difference', 'intersection', 'isdisjoint', 'issubset', 'issuperset', 'symmetric_difference', 'union']
frozenset These methods and methods of collection set The function of the method with the same name in the collection is the same .
In two cases, you can use fronzenset:
The following program demonstrates frozenset Usage of :
s = {
'Python', 'C', 'C++'}
fs = frozenset(['Java', 'Shell'])
s_sub = {
'PHP', 'C#'}
# towards set Add... To the collection frozenset
s.add(fs)
print('s =', s)
# for set Add child to collection set aggregate
s.add(s_sub)
print('s =', s)
Running results :
s = {
'Python', frozenset({
'Java', 'Shell'}), 'C', 'C++'}
Traceback (most recent call last):
File "C:\Users\mozhiyan\Desktop\demo.py", line 11, in <module>
s.add(s_sub)
TypeError: unhashable type: 'set'
It should be noted that ,set The elements of the collection itself must be immutable , therefore set The element of cannot be set, Can only be frozenset. The first 6 Line code to set Add frozenset No problem , because frozenset It's immutable ; however , The first 10 In line of code, try to set Add to the cake set, This is not allowed , because set Is variable .
Dragon Boat Festival welfare !