set and frozenset

>>> x = set("A Python")
>>> x
set(['A', ' ', 'h', 'o', 'n', 'P', 't', 'y'])

Sets are implemented in a way, which doesn't allow mutable objects.

>>> name = set((["name1", "name2"], "name3"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> name = set((("name1", "name2"), "name3"))
>>>

Some operations of set

>>> name = {'LiLei', 'HanMeimei'}
>>> course = {'LiLei', 'LiMing'}
>>> name.difference(course)
set(['HanMeimei'])
>>> name.union(course)
set(['LiLei', 'LiMing', 'HanMeimei'])
>>> math = {'LiLei'}
>>> math.issubset(course)
True
>>> course.issuperset(math)
True
>>> english = {'WuWei'}
>>> english.isdisjoint(math)
True
>>> name.intersection(course)
set(['LiLei'])
>>> name.symmetric_difference(course)
set(['LiMing', 'HanMeimei'])
>>> 

Frozensets are like sets except that they cannot be changed, they are immutable

>>> name = frozenset(["name1", "name2"])
>>> name.add("name3")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'add'
>>> 
>>> x = {"a", "b", "c"}
>>> y = {"a"}
>>> x.difference(y)
set(['c', 'b'])
>>> x -y
set(['c', 'b'])
>>> x.discard("a")
>>> x
set(['c', 'b'])





發佈了82 篇原創文章 · 獲贊 46 · 訪問量 96萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章