一、集合的定义和基本操作方法
1、定义
- 不同元素组成(会自动去掉重复的元素)
- 无序
- 集合中的元素必须是不可变类型
2、集合的格式举例
x = {1,2,5,"hello","word"}
3、集合的基本操作
1)不同类型转变为集合的方法举例
x = set("hello") #转变为普通可变集合
x = set(["hello","hello","word"]) #转变为普通可变集合
x = frozenset("hello") #转变为特殊不可变集合
2)增加集合的元素
x = {1,2,3,5}
x.add("y")
3)清除集合
x = {1,2,3,5}
x.clear()
4)复制集合
x = {1,2,3,5}
x1 = x.copy()
5)随机删除集合元素
x = {1,2,3,5}
x.pop()
6)指定删除集合元素,没找到要删除的元素时会报错
x = {1,2,3,5}
x.remove(5)
7)指定删除集合元素,没找到要删除的元素时不会报错
x = {1,2,3,5}
x.discard(8)
8)求交集
A = ['a','b','c','d']
B = ['a','b','e']
A1 = set(A)
B1 = set(B)
print(A1,B1)
print(A1.intersection(B1))
print(A1 & B1)
9)求并集
A = ['a','b','c','d']
B = ['a','b','e']
A1 = set(A)
B1 = set(B)
print(A1,B1)
print(A1.union(B1))
print(A1 | B1)
10)求差集
A = ['a','b','c','d']
B = ['a','b','e']
A1 = set(A)
B1 = set(B)
print(A1,B1)
print(A1.difference(B1)) #A1-B1的差集
print(A1 - B1)
print(B1.difference(A1)) #B1-A1的差集
print(B1 - A1)
11)求交叉补集
A = ['a','b','c','d']
B = ['a','b','e']
A1 = set(A)
B1 = set(B)
print(A1,B1)
print(A1.symmetric_difference(B1))
print(A1 ^ B1)
备注:symmetric_difference_update 是求交叉补集并复制给原值,例如将A1和B1的交叉补集复制给A1,此处省略;
12)将A1和B1的差集赋值给A1
A = ['a','b','c','d']
B = ['a','b','e']
A1 = set(A)
B1 = set(B)
print(A1,B1)
A1.difference_update(B1) #相当于 A1 = A1 - B1
print(A1)
13)将A1和B1的交集复制给A1
A = ['a','b','c','d']
B = ['a','b','e']
A1 = set(A)
B1 = set(B)
print(A1,B1)
A1.intersection_update(B1) #相当于 A1 = A1 & B1
print(A1)
14)有交集返回True,无交集返回False
A = ['a','b','c','d']
B = ['a','b','e']
A1 = set(A)
B1 = set(B)
print(A1,B1)
print(A1.isdisjoint(B1))
15)判断A1是否是是B1的子集,即A1 <= B1成立则显示True,否则显示False
A = [1,2,3]
B = [1,2,3,4,5]
A1 = set(A)
B1 = set(B)
print(A1,B1)
print(A1.issubset(B1))
16)判断A1是否是是B1的父集,即A1 >= B1成立则显示True,否则显示False
A = [1,2,3,4,5]
B = [1,2,3,4,5]
A1 = set(A)
B1 = set(B)
print(A1,B1)
print(A1.issuperset(B1))
17)将B1的多个值增加到A1
A = [1,2,3,4,5]
B = [1,2,3,4,5]
A1 = set(A)
B1 = set(B)
print(A1,B1)
A1.update(B1)
print(A1)
备注:与add相比的区别,add一次只能增加一个值,update一次可以增加多个值;
18)使用集合对列表进行去重(不考虑列表内容的顺序)
x = ["a","b","a","a"]
x = list(set(x))