Python 基础知识全篇-集合(Sets)

2020-05-20  本文已影响0人  BABYMISS

集合对象是一系列无序的,离散的哈希对象的集合。常用于成员测试,移除重复元素和一些算术运算例如交,并,差和对称差等。

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)

上一篇下一篇

猜你喜欢

热点阅读