特性
- 唯一性,数据不重复,自动去重
- 无序
- 集合可以使用的数据(str, int, float, bool,tuple, complex, frozenset())
- 不能访问,删除,修改,添加
序列操作
- in
- len() 检测集合长度
- max() 最大值
- min() 最小值
- set() 类型改变为集合类型
集合基本操作
- add() 向集合中添加一个元素
- pop() 随机删除集合中的值
s = {1, 2, 3, 4, 5}
print( s.pop() )
# 1
print(s)
# {2, 3, 4, 5}
- remove() 移除集合中指定的值,移除的数据不存在,不报错
- discard() 移除集合中指定的值,移除的数据不存在,不报错
- clear() 清空集合
- copy() 复制集合
集合运算函数
- difference() 差集
s1 = {1, 2, 3, 4, 5}
s2 = {5, 6, 7, 8, 9}
print( s1.difference(s2) )
# {1, 2, 3, 4}
print( s2.difference(s1) )
# {8, 9, 6, 7}
- difference_update() 差集更新
s1 = {1, 2, 3, 4, 5}
s2 = {5, 6, 7, 8, 9}
s1.difference_update(s2)
print(s1)
# {1, 2, 3, 4}
- intersection() 交集
s1 = {1, 2, 3, 4, 5}
s2 = {5, 6, 7, 8, 9}
print( s1.intersection(s2) ) # {5}
print( s2.intersection(s1) ) # {5}
- intersection_update() 交集更新
s1 = {1, 2, 3, 4, 5}
s2 = {5, 6, 7, 8, 9}
s1.intersection_update(s2)
print(s1)
#{5}
- union() 并集
s1 = {1, 2, 3, 4, 5}
s2 = {5, 6, 7, 8, 9}
print( s1.union(s2) )
# {1, 2, 3, 4, 5, 6, 7, 8, 9}
print( s2.union(s1) )
# {1, 2, 3, 4, 5, 6, 7, 8, 9}
*update() 并集更新
s1 = {1, 2, 3, 4, 5}
s2 = {5, 6, 7, 8, 9}
s1.update(s2)
print(s1)
# {1, 2, 3, 4, 5, 6, 7, 8, 9}
- issuperset() 超集
- issubset() 子集
s1 = {1, 2, 3, 4, 5, 6, 7, 8, 9,0 }
s2 = {5, 6, 7, 8, 9}
print( s1.issuperset(s2) ) # True
print( s2.issubset(s1) ) #true
- isdisjoint() 非相交集合
s1 = {1, 2, 3, 4}
s2 = {6, 7, 8, 9}
print( s1.isdisjoint(s2) )
# True
- symmetric_difference() 两个集合不想交的集合
s1 = {1, 2, 3, 4, 5}
s2 = {5, 6, 7, 8, 9}
print( s1.symmetric_difference(s2) )
# {1, 2, 3, 4, 6, 7, 8, 9}
print( s2.symmetric_difference(s1) )
# {1, 2, 3, 4, 6, 7, 8, 9}
- symmetric_difference_update() 集合不想交更新操作
s1 = {1, 2, 3, 4, 5}
s2 = {5, 6, 7, 8, 9}
s1.symmetric_difference_update(s2)
print(s1)
# {1, 2, 3, 4, 6, 7, 8, 9}
冰冻集合 frozenset
可以传入列表