set 集合 无序 不可重复 可以用来过滤元素
语法 set= (,,) 当set集合只有一个数值是,数值后加,号
定义空的set集合 set1=set()
集合.add(va) 把va添加到set集合中 单个元素的增加用add方法,
set1 = {1,2,3,4,5,6}
set1.add(10)
print(set1)
集合.remove(va) 把va从集合中删除
set1 = {1,2,3,4,5,6}
set1.remove(2)
print(set1)
| 并集
set1 = {1,2,3,4,5,6}
set2 = {3,4,5,6,7,8}
ret = set1 | set2
print(ret)
& 交集
set1 = {1,2,3,4,5,6}
set2 = {3,4,5,6,7,8}
ret = set1 & set2
print(ret)
- 差集
set1 = {1,2,3,4,5,6}
set2 = {3,4,5,6,7,8}
ret = set1 - set2
ret1 = set2-set1
print(ret)
print (ret1)
对序列的增加用update方法
# 集合.update(x) 把x中的内容并入到前一个集合中,x可以是列表,集合
set1 = {1,2,}
print(type(set1))
x= {1:2,2:3}
set1.update(x)
print(set1)
#集合.discard(x) 把x从集合中移除
set1 = {1,2,3,4,5,6}
x=3
set1.discard(x)
print(set1)
#集合.pop() 随机删除集中的值,并返回
set1 = {7,2,3,4,5,6}
ret=set1.pop()
print(set1)
print(ret)
# 集合.clear() 清空集合
set1 = {7,2,3,4,5,6}
set1.clear()
print(set1)
# in 判断值是否在集合中
set1 = {7,2,3,4,5,6}
print(7 in set1)
set1 = {7,2,3,4,5,6}
x=[1,2,3,4,]
ret=set1.union(x) # 集合.union(x) 返回集合 与x 的交集
ret1=set1.intersection(x) # 集合.intersection(x) 返回集合 与x 的并集
ret3 = set1.difference(x) # 集合1.difference(x) 返回值在集合1而不再x中的值
print (ret)
print (ret1)
print (ret3)
set1 = {7,2,3,4,5,6}
x=[1,2,3,4,]
# 集合1.symmetric_difference(x) 返回只在集合1或x中的值
ret=set1.symmetric_difference(x)
print(ret)
# 集合.issubset(x)判断集合是不是x的子集
set1 = {7,2,3,4,5,6}
x=[1,2,3,4,]
y={2,3}
print(set1.issubset(x))
print(y.issubset(set1))
# 集合.issuperset(x)判断x是不是集合的子集
print(set1.issuperset(x))