集合:一个无序的,不重复的数据组合
- 去重,列表变集合,自动去重
- 关系测试,测试两组数据之间的交集,差集,并集等关系
去重
set0 = set("hello") # 创建字符集合
print("set0:", set0) # ->set0: {'e', 'l', 'h', 'o'}
list1 = [1, 2, 3, 1, 2]
set1 = set(list1) # 创建数值集合
print(type(set1), set1) # -><class 'set'> {1, 2, 3}
set2 = {1, 2, 4, 0}
set3 = {1, 2}
print("set1:", set1) # ->set1: {1, 2, 3}
print("set2:", set2) # ->set2: {0, 1, 2, 4}
print("set3:", set3) # ->set3: {1, 2}
关系测试
# 交集
print("set1 ∩ set2:", set1.intersection(set2)) # ->set1 ∩ set2: {1, 2}
print("set1 & et2:", set1 & set2) # ->set1 & et2: {1, 2}
# 并集
print("set1 ∪ set2:", set1.union(set2)) # ->set1 ∪ set2: {0, 1, 2, 3, 4}
print("set1 | set2:", set1 | set2) # ->set1 | set2: {0, 1, 2, 3, 4}
# 差集 in set1 but no in set2
print("set1-set2:", set1.difference(set2)) # ->set1-set2: {3}
print("set2-set1:", set2.difference(set1)) # ->set2-set1: {0, 4}
print("set1-set2:", set1 - set2) # ->set1-set2: {3}
print("set2-set1:", set2 - set1) # ->set2-set1: {0, 4}
# 对称差集 二者中不相交的部分
print("set1-set2 ∪ set2-set1:", set1.symmetric_difference(set2))
# ->set1-set2 ∪ set2-set1: {0, 3, 4}
print("set1 ^ set2:", set1 ^ set2) # ->set1 ^ set2: {0, 3, 4}
# 子集
print("set3∈set1?:",set3.issubset(set1)) # ->set3∈set1?: True
print("set3 <= set1:",set3.issubset(set1)) # ->set3 <= set1: True
# 父集
print("set3∈set1?:",set1.issuperset(set3)) # ->set3∈set1?: True
print("set1 >= set3:",set1.issuperset(set3)) # ->set1 >= set3: True
# 相等
print("set1 == set2", set1 == set2) #->set1 == set2 False
print("set1 != set2", set1 != set2) #->set1 != set2 True
# 不相交
set4 = {5, 6, 7}
print(set4) # ->{5, 6, 7}
print("set1∩set2==null?", set1.isdisjoint(set2))
# ->set1∩set2==null? False
print("set1∩set4==null?", set1.isdisjoint(set4))
# ->set1∩set4==null? True
基本操作
# 添加
print(set1) # ->{1, 2, 3}
set1.add(5) # 添加一项
print(set1) # ->{1, 2, 3, 5}
set1.update([6, 7, 8, 8]) #添加多项
print(set1) # ->{1, 2, 3, 5, 6, 7, 8}
# 删除
set1.remove(5) # 指定删除,不存在会报错
print(set1) # ->{1, 2, 3, 6, 7, 8}
set1.pop() # 随意删除
print(set1) # ->{2, 3, 6, 7, 8}
set1.discard(888) # 指定删除,不存在不会报错
# 长度
print(len(set1)) # ->5
# 成员检查,字符串,列表,集合,字典
print(6 in set1) # ->True
print(9 not in set1) # ->True