4. 集合操作
集合是一个无序的,不重复的数据组合,它的主要作用如下:
1. 去重,把一个列表变成集合,就自动去重了
2. 关系测试,测试两组数据之前的交集、差集、并集等关系
1-1
list_1 = [1,4,5,7,3,6,7,9]
list_1 = set(list_1)
print(list_1,type(list_1))
--->
{1, 3, 4, 5, 6, 7, 9} <class 'set'>
集合有点像字典,其实不是字典,集合也是无序的
1-1-1
1ist_1 = [1,4,5,7,3,6,7,9]
list_1 = set(list_1)
list_2 = set([2,6,0,66,22,8,4])
print(list_1,list_2)
--->
{1, 3, 4, 5, 6, 7, 9} {0, 2, 66, 4, 6, 8, 22}
1-1-1-1
如何快速取出交集?
# 交集
print(list_1.intersection(list_2))
--->
{4, 6}
1-1-1-2
# 并集
print(list_1.union(list_2))
--->
{0, 1, 2, 3, 4, 5, 6, 7, 66, 9, 8, 22}
两个集合合并一起了
1-1-1-3
# 差集 in list_1 but not in list_2
print(list_1,list_2)
print(list_1.difference(list_2))
--->
{1, 3, 4, 5, 6, 7, 9} {0, 2, 66, 4, 6, 8, 22}
{1, 3, 5, 7, 9}
1-1-1-4
# 差集 in list_2 but not in list_1
print(list_1,list_2)
print(list_2.difference(list_1))
--->
{1, 3, 4, 5, 6, 7, 9} {0, 2, 66, 4, 6, 8, 22}
{0, 2, 66, 8, 22}
1-1-1-5
# 子集
print(list_1,list_2)
print(list_1.issubset(list_2))
--->
{1, 3, 4, 5, 6, 7, 9} {0, 2, 66, 4, 6, 8, 22}
False
1-1-1-6
# 父集
print(list_1,list_2)
print(list_1.issuperset(list_2))
--->
{1, 3, 4, 5, 6, 7, 9} {0, 2, 66, 4, 6, 8, 22}
False
list_3 = set([1,3,7])
print(list_3.issubset(list_1))
print(list_1.issuperset(list_3))
--->
True
True
1-1-1-7
# 对称差集
list_1 = [1,4,5,7,3,6,7,9]
list_1 = set(list_1)
list_2 = set([2,6,0,66,22,8,4])
print(list_1,list_2)
print(list_1.symmetric_difference(list_2))
--->
{1, 3, 4, 5, 6, 7, 9} {0, 2, 66, 4, 6, 8, 22}
{0, 1, 2, 66, 3, 5, 8, 7, 9, 22}
# 去掉了交集,取出互相没有的,放一起,去掉重复的
# 关系就这些,交集,并集,差集,父集,子集,对称差集
2-1
list_1 = [1,4,5,7,3,6,7,9]
list_1 = set(list_1)
list_2 = set([2,6,0,66,22,8,4])
list_3 = set([1,3,7])
list_4 = set([5,6,8])
print(list_3.isdisjoint(list_4))
--->
True
2-1-1
list_3 = set([1,3,7])
list_4 = set([5,6,7,8])
print(list_3.isdisjoint(list_4))
--->
False
2-2
用符号表示交集
# 交集
list_1 = [1,4,5,7,3,6,7,9]
list_1 = set(list_1)
list_2 = set([2,6,0,66,22,8,4])
print(list_1 & list_2)
--->
{4, 6}
2-2-1
用符号表示并集
# 并集
list_1 = [1,4,5,7,3,6,7,9]
list_1 = set(list_1)
list_2 = set([2,6,0,66,22,8,4])
print(list_2 | list_1)
--->
{0, 1, 2, 66, 4, 3, 6, 5, 8, 7, 9, 22}
2-2-2
用符号求差集
# difference
list_1 = [1,4,5,7,3,6,7,9]
list_1 = set(list_1)
list_2 = set([2,6,0,66,22,8,4])
print(list_1 - list_2) # in list 1 but not in list 2
--->
{1, 3, 5, 7, 9}
2-2-3
用符号求 对称差集
# 对称差集
list_1 = [1,4,5,7,3,6,7,9]
list_1 = set(list_1)
list_2 = set([2,6,0,66,22,8,4])
print(list_1 ^ list_2)
--->
{0, 1, 2, 66, 3, 5, 8, 7, 9, 22}
# 顺序同样没关系
3-1
我们对集合还可以进行 增删改查
list_1 = set([1,4,5,7,3,6,7,9])
list_2 = set([2,6,0,66,22,8,4])
list_1.add(999)
print(list_1)
# 添加位置是无序的
--->
{1, 3, 4, 5, 6, 7, 999, 9}
3-1-1
添加多项
list_1 = set([1,4,5,7,3,6,7,9])
list_2 = set([2,6,0,66,22,8,4])
list_1.update([888,777,555])
print(list_1)
--->
{1, 3, 4, 5, 6, 7, 9, 777, 555, 888}
3-1-2
删除
使用 remove() 可以删除一项
t.remove('H') # 去重
3-1-3
x in s
测试 x 是否是 s 的成员
x not in s
测试 x 是否不是 s 的成员
s.copy()
返回 set "s" 的一个浅复制
3-1-4
list_1.discard()
remove 如果不存在会报错
discard 如果不存在,不会报错