集合
1.什么是集合(set)
集合是容器型数据类型, 将{}作为容器的标志里面多个元素用逗号隔开: {元素1, 元素2, 元素3, …}
可变的; 无序的
元素: 不可变的数据; 唯一性
1) 集合
x = {} # 空字典
s1 = set() # 空集合
print(s1) # set()
2) 元素是不可变的
s2 = {10, ‘abc’, (1, 2)}
print(s2) # {(1, 2), ‘abc’, 10}
报错, 列表可变不能作为集合元素
s3 = {10, 'abc', [1, 2]}
print(s3) # TypeError: unhashable type: 'list'
3) 元素是唯一的
s4 = {10, 20, 30, 10, 50}
print(s4) # {10, 20, 50, 30}
集合去重
nums = [2, 1, 30, 10, 2, 1, 55, 60]
nums = list(set(nums))
print(nums) # [1, 2, 10, 55, 60, 30]
4) 集合是无序的
print({1, 3, 5} == {5, 1, 3}) # True
2.集合的增删改查
1) 查 - 集合只能遍历
补充: 通过for循环遍历序列的时候,都是先将序列转换成列表, 然后遍历列表
games = {'QQ炫舞', '扫雷', '贪吃蛇', '我的世界', '侠盗猎车手', '红警'}
for x in games:
print("x:", x)
2) 增
集合.add(元素) - 在集合中添加指定的元素
games = {'lol', 'cs', 'dnf', 'cs:go'}
games.add('gta')
print(games) # {'cs', 'gta', 'lol', 'cs:go', 'dnf'}
集合.update(序列) - 将序列中所有元素添加到集合中
games.update({'cf', 'cod'})
print(games) # {'cs', 'gta', 'lol', 'cs:go', 'cod', 'dnf', 'cf'}
3) 删
集合.remove(元素) - 删除集合中指定的元素(元素不存在会报错)
集合.discard(元素) - 删除集合中指定的元素(元素不存在不会报错)
games = {'QQ炫舞', '扫雷', '贪吃蛇', '我的世界', '侠盗猎车手', '红警'}
games.remove('贪吃蛇')
print(games) # {'QQ炫舞', '扫雷', '侠盗猎车手', '我的世界', '红警'}
4) 改 - 先删除原来的,在添加新的
games = {‘QQ炫舞’, ‘扫雷’, ‘贪吃蛇’, ‘我的世界’, ‘侠盗猎车手’, ‘红警’}
games.remove(‘扫雷’)
games.add(‘部落冲突’)
3.数学集合运算
python中的集合支持数学中的集合运算:&(交集)、|(并集)、-(差集)、^(对称差集), >, <, >=, <=(判断包含关系)
set1 = {1, 2, 3, 4, 5, 6, 7}
set2 = {4, 5, 6, 7, 8, 9, 10}
1) 集合1 & 集合2 - 求两个集合的公共部分
print(set1 & set2) # {4, 5, 6, 7}
2) 集合1 | 集合2 - 合并两个集合产生一个新的集合
print(set1 | set2) # {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
3) 集合1 - 集合2 - 求集合1去掉包含在集合2中的元素剩下的元素
print(set1 - set2) # {1, 2, 3}
print(set2 - set1) # {8, 9, 10}
4) 集合1 ^ 集合2 - 将两个集合合并后去掉公共部分
print(set1 ^ set2) # {1, 2, 3, 8, 9, 10}
5)
集合1 > 集合2 - 判断集合2是否是集合1的真子集
集合1 < 集合2 - 判断集合1是否是集合2的真子集
集合1 >= 集合2 - 判断集合2是否是集合1的子集
集合1 >= 集合2 - 判断集合1是否是集合2的子集
print({1, 2, 3, 4} > {1, 2}) # True
print({1, 2, 3, 4} > {1, 2, 3, 4}) # False
print({1, 2, 3, 4} >= {1, 2, 3, 4}) # True
print({1, 2, 3, 4} >= {1, 2}) # True
print({100, 200, 300} > {1, 2}) # False