python中不可变集合

 

1、

>>> a = {1,2,3}
>>> a
{1, 2, 3}
>>> type(a)
<class 'set'>
>>> a.add(4)
>>> a
{1, 2, 3, 4}
>>> b = frozenset({1,2,3})    ## 不可变集合
>>> b
frozenset({1, 2, 3})
>>> type(b)
<class 'frozenset'>
>>> b.add(4)
Traceback (most recent call last):
  File "<pyshell#845>", line 1, in <module>
    b.add(4)
AttributeError: 'frozenset' object has no attribute 'add'
>>> c = frozenset(a)     ## 不可变集合
>>> c
frozenset({1, 2, 3, 4})
>>> c.add(4)
Traceback (most recent call last):
  File "<pyshell#848>", line 1, in <module>
    c.add(4)
AttributeError: 'frozenset' object has no attribute 'add'

 

上一篇:992. K 个不同整数的子数组


下一篇:Python基础知识:新手学Python时常见的语法错误和异常