集合對象是一系列無序的羡鸥,離散的哈希對象的集合。常用于成員測試忠寻,移除重復元素和一些算術運算例如交惧浴,并,差和對稱差等奕剃。
shapes = ['circle', 'square', 'triangle', 'circle']
set_of_shapes = set(shapes)
set_of_shapes
shapes = {'circle', 'square', 'triangle', 'circle'}
for shape in shapes:
? ? print(shape)
set_of_shapes.add('polygon')
print(set_of_shapes)
存在性檢查
# Test if circle is IN the set (i.e. exist)
print('Circle is in the set: ', ('circle' in set_of_shapes))
print('Rhombus is in the set:', ('rhombus' in set_of_shapes))
常用操作
favourites_shapes = set(['circle','triangle','hexagon'])
# Intersection
set_of_shapes.intersection(favourites_shapes)
# Union
set_of_shapes.union(favourites_shapes)
# Difference
set_of_shapes.difference(favourites_shapes)