集合
创建空集合用set()。因为{}用来创建字典了。
主要作用是去重,保存不重复的数据
一.增加数据
1.add()
s1 = {10,20,30,10}
s1.add(40)
s1.add(20)
print(s1)
#{10,20,30,40}
因为集合有去重功能,所以,当向集合内追加的数据是当前集合已有数据的话,则不进行任何操作。
2.update(),追加的数据是序列
s1 = {10,20,30}
s1.update(40) #报错
s1.update([40,50]) #{10,20,30,40,50}
二.删除数据
1.remove(),删除集合中的指定数据,如果数据不存在则报错
s1 = {10,20,30}
s1.remove(10) #{20,30}
s1.remove(10)#报错
2.discard(),删除集合中的指定数据,如果数据不存在也不会报错
s1 = {10,20,30}
s1.discard(10) #{20,30}
s1.discard(10)#不报错
3.pop(),随机删除集合中的某个数据,并返回这个数据
s1 = {10,20,30}
ss = s1.pop()
print(ss) #随机删除的数据
3.查找数据
in:判断数据在集合序列
not in:判断数据不在集合序列
s2 = {10,20,30,40,60}
print(10 in s1)
print(10 not in s1)