集合类型内置方法
集合基本用不到
1.作用
用于关系运算的集合体,由于集合内的元素无序且集合元素不可重复,因此集合可以去重,但是去重后的集合会打乱原来元素的顺序。
2.定义
#以{}用逗号隔开不可变数据类型
s={1,2,1,'a','b','c'}
print(s)
去重
lis = [1,2,3,1,3]
print(set(lis))
print(list(set(lis)))
print(set())
s = {} # 空大括号是字典,不是集合,定义空集合必须得用set()
print(type(s))
3.内置方法
pythoners={'jason','nick','tank','sean'}
linuxers={'nick','egon','kevin'}
print(pythoners|linuxers) #并集
print(pythoners.union(linuxers))
{'sean', 'egon', 'nick', 'jason', 'tank', 'kevin'}
{'sean', 'egon', 'nick', 'jason', 'tank', 'kevin'}
print(pythoners & linuxers) # 交集
print(pythoners.intersection(linuxers))
{'nick'}
{'nick'}
print(pythoners - linuxers) # 差集
print(pythoners.difference(linuxers))
{'jason', 'sean', 'tank'}
{'jason', 'sean', 'tank'}
print(pythoners ^ linuxers) # 交叉补集
print(pythoners.symmetric_difference(linuxers))
{'jason', 'sean', 'kevin', 'egon', 'tank'}
{'jason', 'sean', 'kevin', 'egon', 'tank'}
了解
s = {1,2,3}
s.add(4)
print(s)
{1,2,3,4}
pythoners={'jason','nick','tank','sean'}
linuxers={'nick','egon','kevin'}
pythoners.pop()
print(pythoners)
{'sean', 'tank', 'jason'}
pythoners.update(linuxers)
print(pythoners)
{'nick', 'sean', 'kevin', 'egon', 'jason', 'tank'}
pythoners.clear() # 清空
print(pythoners)
set()
print(pythoners.copy())
{'nick', 'sean', 'tank', 'jason'}
pythoners.remove('nickk')
print(pythoners)
报错
pythoners.discard('nickk')
print(pythoners)
{'sean', 'jason', 'nick', 'tank'}
remove和discard区别是remove没有会报错,discard没有不会报错
pythoners = {'jason', 'nick', 'tank', 'sean'}
pythoners2 = {'jason', 'nick', 'tank', 'sean','nick2'}
print(pythoners.issubset(pythoners2)) # 子集
print(pythoners.issuperset(pythoners2)) # 父集
True
False
pythoners = {'jason', 'nick', 'tank', 'sean'}
linuxers = {'nick', 'egon', 'kevin'}
pythoners.difference_update(linuxers)
print(pythoners)
pythoners.symmetric_difference_update(linuxers)
print(pythoners)
'tank', 'jason', 'sean'}
{'tank', 'jason', 'kevin', 'sean', 'egon', 'nick'}
pythoners = {'jason', 'tank', 'sean'}
linuxers = {'nick', 'egon', 'kevin'} # 集合没有共同的部分返回True,否则返回False
res = pythoners.isdisjoint(linuxers)
print(res)
4.存一个值还是多个值
多个值
5.有序or无序
无序
6.可变or不可变
可变
s = {1,2}
print(id(s))
s.add(3)
print(id(s))
2175853453096
2175853453096