[email protected]集合(set)

集合


1. 集合set的定义

• 集合是不重复的数据结构;
#定义方式一:
s = {}  //内容为空时,表示为字典类型
s = {1,2,3}  //集合
#定义方式二:
工厂方式定义集合时,括号里面时可迭代对象
s = set()  //定义一个空集合
其余如下:
[email protected]集合(set)

应用:如何实现列表去重?
• 转换为集合数据类型:set(列表)
• 字典的fromkeys方法实现
#列表去重一:
[email protected]集合(set)
#列表去重二:

[email protected]集合(set)


2. 集合的特性

• 集合是无序的,不重复的数据类型
• 因此不支持索引和切片,也不支持重复和连接
• 支持成员操作符
• 支持for循环
[email protected]集合(set)
[email protected]集合(set)

3. 集合的增删查


1)增加
s.add()
[email protected]集合(set)
[email protected]集合(set)
s.update()
[email protected]集合(set)

2)查-关系测试操作
已知:
[email protected]集合(set)
#交集
s1 & s2
s1.intersection(s2)
s1.intersection_update(s2) //更新s1为s1与s2交集
[email protected]集合(set)
#并集
s1 | s2
s1.union(s2)
[email protected]集合(set)
#差集
s1 - s2
s2 - s1
s1.difference(s2)
s2.difference(s1)
s1.difference_update(s2) //更新s1为s1与s2差集
[email protected]集合(set)
[email protected]集合(set)
#对等差分
s1 ^ s2
s1.symmetric_difference(s2)
s1.symmetric_difference_update(s2) //更新s1为s2与s2的对等差差分
[email protected]集合(set)
#其他
s1.issubset(s2) //s1是否为s2的子集
s1.issuperset(s2) //s1是否为s2的父集
s1.isdisjoint(s2) //s1与s2是否无交集
[email protected]集合(set)

3)删除
• s.pop //随即删除集合中的元素
[email protected]集合(set)
• s.remove() //删除集合指定元素,如果不存在,则报错
[email protected]集合(set)
• s.discard() //删除集合指定元素,如果不存在,do nothing
[email protected]集合(set)
• s.clear() //清空集合元素
[email protected]集合(set)

4. 总结

1)是否为可变数据类型
• 可变数据类型:列表,字典,集合
• 不可变数据类型:数值类型,字符型,元组
可变数据类型实现某个功能,直接改变可变数据类型;
不可变数据类型实现某个功能,需要将结果赋值给另一个变量;
2)是否实现for循环
• 可迭代数据类型:str,list,tuple,dict,set
• 不可迭代数据类型:数值类型
3)是否支持索引,切片,重复和连接特性
• 有序数据类型:str,list,tuple
• 无序数据类型:dict,set