集合基本用不到,考试会考
作用
就是存储一大堆元素的东西,容器数据类型
定义方式
以{}用逗号隔开不可变数据类型
s = {1,2,1,'a','a','c'}
print(s)
去重 #用得到
乱序
lis = [1,2,3,1,3]
print(set(lis))
print(list(set(lis)))
s = {} # 空大括号是字典,不是集合,定义空集合必须得用set()
print(type(s))
内置方法 不建议使用(.)点出来的方法(会考)
pythoners = {'jason','nick','tank','sean'}
linuxers = {'nick','egon','kevin'}
print(pythoners | linuxers) # 并集
print(pythoners.union(linuxers))
print(pythoners & linuxers) # 交集
print(pythoners.intersection(linuxers))
print(pythoners - linuxers) # 差集
print(pythoners.difference(linuxers))
print(pythoners ^ linuxers) # 交叉补集
print(pythoners.symmetric_difference(linuxers))
s ={1,2,3}
s.add(4)
print(s) # 结果为{1,2,3,4}
了解(不会考)
pythoners = {'jason','nick','tank','sean'}
linuxers = {'nick','egon','kevin'} # 老刘
print(pythoners.pop()) # 随即删除
print(pytohners.update(linuxers))
print(pythoners.chear()) # 清空
print(pythoners.copy()) # 复制
print(pythoners.remove('nick')) # 指定删除;不会报错
print(pythoners.discard('nick')) # 会报错
pythoners = {'jason','nick','tank','sean'}
pythoners2 = ['jason','nick','tank','sean','nick2']
print(pythoners.issubset(pythoners2)) # 是否为子集;你有的我只有一部分
print(pythoners.idduperset(pythoners2)) # 是否为父集
pythoners = {'jason','nick','tank','sean'}
linuxers = {'nick','egon','kevin'} # 老刘
print(pytohners.difference_update(linuxers)) # 差集;A有的B没有
print(pythoners.symmetric_difference_update(linuxers)) # 去除相同
pythoners = {'jason','nick','tank','sean'}
linuxers = {'nick','egon','kevin'} # 老刘
res = pythoners.isdisjoint(linuxers) # 有相同的返回False,否则返回True
print(res)
一个值还是多个值
多个值
有序or无序
无序
可变or不可变(重点)
可变
s = {1,2}
print(id(s))
s.add(3)
print(id(s)) # 内存地址相同则‘可变’
标签:nick,内置,jason,pythoners,数据类型,print,sean,集合,linuxers
From: https://www.cnblogs.com/hanyingshuo/p/17687463.html