标签:drive sub 交集 删除 cal 必须 upd ace 删除元素
>>> s= {1,2,3,4,5,2}
>>> s
{1, 2, 3, 4, 5} #自动去重
>>> s.add(9) #添加内容
>>> s
{1, 2, 3, 4, 5, 9} # 9添加进来了
>>> s.add(2) #添加一个已经存在的2,添加会失败
>>> s
{1, 2, 3, 4, 5, 9}
>>> s
{1, 2}
>>> s.add(3) # 通过add添加
>>> s
{1, 2, 3}
>>> s = {1,2,3,4,5,66,77}
>>> s
{1, 2, 3, 4, 5, 66, 77}
>>> s.update([1,2,3,6,88,99]) # update
>>> s
{1, 2, 3, 4, 5, 66, 6, 99, 77, 88} # 把没有的元素都加进去了
集合只能添加不可变数据
>>> s
{1, 2}
>>> s.add([1,2,3]) #集合只能添加不可变数据
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: ‘list‘
copy
>>> s
{1, 2}
>>> s1 = s.copy() #copy
>>> s1
{1, 2}
删除元素
>>> s
{1, 2, 3, 4, 5, 66, 6, 99, 77, 88}
>>> s.discard(1) #删除元素,删除不存在的元素也不会报错
>>> s = {1,2,3}
>>> s.pop() #随便删除一个元素, 集合为空会报错
1
>>> s
{2, 3}
>>> s = {1,2,3}
>>> s.clear() #清空
>>> s
set()
交集
iphone7 = {‘alex‘, ‘rain‘, ‘jack‘, ‘old_driver‘}
iphone8 = {‘alex‘, ‘jack‘, ‘shanshan‘, ‘old_boy‘}
#交集
print(iphone7.intersection(iphone8)) #{‘jack‘, ‘alex‘}
print(iphone7 & iphone8) # {‘jack‘, ‘alex‘}
差集
iphone7 = {‘alex‘, ‘rain‘, ‘jack‘, ‘old_driver‘}
iphone8 = {‘alex‘, ‘jack‘, ‘shanshan‘, ‘old_boy‘}
print(iphone7.difference(iphone8)) #{‘old_driver‘, ‘rain‘}
print(iphone7 - iphone8) #{‘old_driver‘, ‘rain‘}
print(iphone8.difference(iphone7)) #{‘shanshan‘, ‘old_boy‘}
print(iphone8 - iphone7) #{‘shanshan‘, ‘old_boy‘}
并集
iphone7 = {‘alex‘, ‘rain‘, ‘jack‘, ‘old_driver‘}
iphone8 = {‘alex‘, ‘jack‘, ‘shanshan‘, ‘old_boy‘}
print(iphone7.union(iphone8)) #{‘rain‘, ‘old_boy‘, ‘jack‘, ‘alex‘, ‘old_driver‘, ‘shanshan‘}
print(iphone7 | iphone8) #{‘rain‘, ‘old_boy‘, ‘jack‘, ‘alex‘, ‘old_driver‘, ‘shanshan‘}
对称差集
只买了iPhone7或 iPhone8的人
iphone7 = {‘alex‘, ‘rain‘, ‘jack‘, ‘old_driver‘}
iphone8 = {‘alex‘, ‘jack‘, ‘shanshan‘, ‘old_boy‘}
print(iphone8.symmetric_difference(iphone7)) #{‘old_driver‘, ‘old_boy‘, ‘rain‘, ‘shanshan‘}
print(iphone8 ^ iphone7) #{‘old_driver‘, ‘old_boy‘, ‘rain‘, ‘shanshan‘}
包含关系
>>> a
{1, 2, 3}
>>> 1 in a
True
set.isdisjoint(s): 判断两个集合是不是不相交
set.issuperset(s) : 判断集合是不是包含其他集合,等同于 a>=b
set.issubset(s) :判断集合是不是被其他集合包含,等同于 a<=b
标签:drive sub 交集 删除 cal 必须 upd ace 删除元素
原文地址:https://www.cnblogs.com/friday69/p/9170427.html