python基础-set集合
1.set的创建
2种方式:
se = {11,22,33}
se = set([11,22,33]) #调用的set的__init__方法进行创建
2.set的常用方法
1.add
se = {11,22,33}se.add(44)
print(se) => {33,11,44,22} #因为是无序的,所以执行的结果会不一样,但是44确实被增加到了原set集合中
2.remove
se = {11,22,33}
se.remove(11)
print (se) => {22,33}
se.remove(44) #报错,提示找不到指定的元素
3.discard
se = {11,22,33}se.discard(11)
print (se) => {22,33}se.discard(44)
print (se) => {11,22,33} #找不到指定的元素时,不删除,不报错
4.pop
se = {11,22,33}
se.pop()print (se) => {11,22} #随机出栈一个元素,执行结果可能不相同ret = se.pop()print (ret) => {33} #将出栈的结果打印出来
5.difference
se1 = {11, 22, 33, 44}
se2 = {22, 33, 44, 55}
print(se1.difference(se2)) = > 11 # 打印se1中存在,但是se2中不存在的元素print(se2.difference(se1)) = > 55 # 打印se2中存在,但是se1中不存在的元素
6.difference_update
se1 = {11,22,33,44}
se2 = {22,33,44,55}
se1.difference_update(se2)print (se1) => 11 #将se1中存在,se2中不存在的元素覆写至se1中,更新set集合
7.intersection
se1 = {11,22,33,44}
se2 = {22,33,44,55}
print (se1.intersection(se2)) => {22,33,44} #se1,se2的交集
8.intersection_update
se1 = {11,22,33,44}
se2 = {22,33,44,55}
se1.intersection_update(se2)
print (se1) => {33,44,22} #将se1,se2的交集覆写至se1的集合中
9.union
se1 = {11,22,33,44}
se2 = {22,33,44,55}
print (se1.union(se2)) => {11,22,33,44,55} #se1,se2的并集
上一篇: Python set集合类型操作总结