目录
- 1.作用
- 2.定义方式
- 3.内置方法
- 4.存一个值还是多个值
- 5.有序 or 无序
- 6.可变 or 不可变(重点)
1.作用
是存储一大堆元素的东西,容器数据类型。用于关系运算的集合体,由于集合内的元素无序且集合元素不可重复,因此集合可以去重,但是去重后的集合会打乱原来元素的顺序。
2.定义方式
以{}用逗号隔开不可变数据类型
空大括号是字典,不是集合,定义空集合必须得用set()
s = {1,2,1,'a','a','c'}
print(s)
3.内置方法
## 优先掌握
# 1.长度len
pythoners = {'jason','nick','tank','sean'}
print(len(pythoners))
# 2.成员运算in和not in
print('nick' in pythoners)
pythoners = {'jason','nick','tank','sean'}
linuxers = {'nick','egon','kevin'}
# 3.并集|
print(pythoners | linuxers)
print(pythoners.union(linuxers))
# 4.交集&
print(pythoners & linuxers)
print(pythoners.intersection(linuxers))
# 5.差集
print(pythoners - linuxers)
print(pythoners.difference(linuxers))
# 6.对称差集^
print(pythoners ^ linuxers)
print(pythoners.symmetric_difference(linuxers))
# 7.==
print(pythoners == linuxers)
# 8.父集:>,>=
print(pythoners > linuxers)
print(pythoners >= linuxers)
# 9.子集:<,<=
print(pythoners < linuxers)
print(pythoners <= linuxers)
## 了解
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('nickk') # 没有报错
print(pythoners)
pythoners.discard('nickk') # 没有不报错
print(pythoners)
pythoners = {'jason','nick','tank','sean'}
pythoners2 = {'jason','nick','tank','sean','nick2'}
# 子集
print(pythoners.issubset(pythoners2))
# 父集
print(pythoners.issuperset(pythoners2))
pythoners = {'jason','nick','tank','sean'}
linuxers = {'nick','egon','kevin'}
pythoners.difference_update(linuxers)
print(pythoners)
pythoners.symmetric_difference_update(linuxers)
print(pythoners)
# isdisjoint() 集合没有共同的部分返回True,否则返回False
pythoners = {'jason','nick','tank','sean'}
linuxers = {'nick','egon','kevin'}
res = pythoners.isdisjoint(linuxers)
print(res)
4.存一个值还是多个值
多个值
5.有序 or 无序
无序
6.可变 or 不可变(重点)
可变
s = {1,2}
print(id(s))
s.add(3)
print(id(s))
原文地址:https://www.cnblogs.com/yushan1/p/11305151.html
时间: 2024-10-24 22:12:01