集合类型内置方法

集合

(基本用不到,redis,但是考试会考)

1. 作用

就是存储一大堆元素的东西容器数据类型

2. 定义方式

以{}用逗号隔开不可变数据类型

s = {1,2,1,'a','a','c'}
print(s)

#去重

#乱序

lis = [1,2,3,1,3]
print(set(lis))     #去重
print(list(set(lis)))    #强制类型转换


print(set())    #空集合

s = {}   #空大括号是字典,不是集合,定义空集合必须得用set()
print(type(s))     #<class'dict'>


3. 内置方法

pythoners = {'jason','nick','tank','sean'}
linuxers = {'nick','egon','kevin'}

print(pythoners | linuxers) or print(pythoners.union(linuxers))
#并集  #{'egon','tank','kevin','nick','jeson','sean'}

print(pythoners & linuxers)   #交集    #{'nick'}
print(pythoners.intersection(linuxers))

print(pythoners - linuxers)   #差集     #{'jeson','tank','sean'}
print(pythoners.difference(linuxers))

print(pythoners ^ linuxers)
print(pythoner.symmetric_difference(linuxers))   #了解
#交叉补集   #{'kevin','jason','egon','tank','sean'}


#了解

pythoners = {'jason','nick','tank','sean'}
linuxers = {'nick','egon','kevin'}   #老刘

pythoners.pop()    #随机删除
print(pythoners)

pythoners.update(linuxers)    #相当于并集
print(pythoners)

pythoners.clear()   #清空
print(pythoners)

print(pythoners.copy())   #复制

pythoners.remove('nick')
print(pythoners)

pythoners.discard('nickk')   #没有不报错
print(pythoners)

pythoners = {'jason','nick','tank','sean'}
pythoners2 = {'jason','nick','tank','sean','nick2'}
print(pythoners.issubset(python2))     #子集
print(pythoners.issuperset(pythoners))    #父集



pythoners = {'jason','nick','tank','sean'}
linuxers = {'nick','egon','kevin'}   #老刘
pythoners.difference_update(linuxers)
print(pythoners)       #从这个集合中删除另一个集合的所有元素

pythoners.symmetric_difference_update(linuxers)
print(pythoners)

pythoners.isdisjoint(linuxers)

4. 存一个值还是多个值

多个值

5. 有序or无序

无序

6. 可变or不可变(重点)

可变

s = {1,2}
print(id(s))
s.add(3)
print(id(s))
posted @ 2023-09-06 19:30  陈hao  阅读(16)  评论(0)    收藏  举报