集合的定义:
- 有不同元素组成
- 无序
- 集合中元素必须是不可变类型
创建集合
s = set("hello") print(s) 或 s = {1,2,3,4,3} print(s)
集合的内置方法
1、add
#增加元素 s = {1,2,3,4,5} s.add("reese") print(s) #输出{1, 2, 3, 4, 5, ‘reese‘}
2、clear
#清空 s = {1,2,3,4,5} s.clear() print(s) #输出结果:set()
3、pop
#随机删除 s = {"re",3,4,5,6,8} s.pop() print(s) #输出结果:{4, 5, 6, 8, ‘re‘}
4、remove(指定删除,删除元素不存在会报错)
#指定删除 s = {1,2,3,4,5,7,"neo"} s.remove("neo") print(s) #输出结果:{1, 2, 3, 4, 5, 7}
5、discard
#指定删除,删除元素不存在不会报错 s1 = {1, 2, 3, 4, 5, 7, "neo"} s1.discard("neo") print(s1) s2 = {1, 2, 3, 4, 5, 7, "neo"} s2.discard("neoll") print(s2) #输出结果: {1, 2, 3, 4, 5, 7} {1, 2, 3, 4, 5, 7, ‘neo‘}
6、intersection
s1 = {12, 34, 56, 123, 890} s2 = {354, 45, 78, 34, 123, 90} print(s1 & s2) # 取交集 print(s1.intersection(s2)) #输出结果: {34, 123} {34, 123}
7、union
s1 = {"reese", 123, 567, 89}
s2 = {123, 89, 45, "neo"}
# 取并集
print(s1 | s2)
print(s1.union(s2))
#输出结果:
{‘neo‘, ‘reese‘, 45, 567, 89, 123}
{‘neo‘, ‘reese‘, 45, 567, 89, 123}
8、difference
s1 = {"reese", 123, 567, 89} s2 = {123, 89, 45, "neo"} # 差集 print(s1 - s2) print(s1.difference(s2)) #输出结果: {‘reese‘, 567} {‘reese‘, 567}
9、symmetric_difference
s1 = {"reese", 123, 567, 89} s2 = {123, 89, 45, "neo"} #交叉补集 print("交叉补集",s1^s2) print("交叉补集",s1.symmetric_difference(s2)) #输出结果: 交叉补集 {‘reese‘, 45, ‘neo‘, 567} 交叉补集 {‘reese‘, 45, ‘neo‘, 567}
10、isdisjoint
s1 = {1,2,3} s2 = {4,5,6} s3 = {2,7,0} print(s1.isdisjoint(s2)) print(s1.isdisjoint(s3)) #输出结果: True False
11、issubset
s1 = {1,2,3} s2 = {1,2,3,4} print(s1.issubset(s2)) #s1 是 s2的子集 #输出结果: True