python基础(八)—集合
集合
1.他是无序的,不重复的
2.它里面的元素必须是可哈希的(不变的)但是集合本身是不可哈希的(可变的)
3.集合没有索引,不能更改里面元素只能增加和删除
4.集合可以求交集,并集,差集,反差集
去重: (一般对列表去重)
1.用算法去重
2.转换成集合在转换过来
lis = [1,1,2,2,3,3,3,4,5,6,6,7]
set1 = set(lis)
lis = list(set1)
print(lis)
创建集合
set1 = {1,'asdsa',3,'qwer'}
set1 = set(set1)
增
#.add 直接添加
set1 = {1,'asdsa',3,'qwer'}
set1 = set(set1)
set1.add(1)
print(set1)
#.update #只能是字符串
set1 = {1,'asdsa',3,'qwer'}
set1 = set(set1)
set1.update(1234)
删.
set1 = {1,'asdsa',3,'qwer'} set1 = set(set1)
#.remove按照元素删除
set1.remove(1)
print(set1)
#.pop 随机删除
set1.pop()
print(set1)
#.clear 清空列表
set1.clert()
print(set1)
#del 直接删除
集合不能修改
查:用for循环查
交集 &
set1 = {4,5,6,7,8,9} set2 = {1,2,3,4,5,6}
print(set2.intersection(set1))
print(set1 & set2)
并集 |
set1 = {4,5,6,7,8,9} set2 = {1,2,3,4,5,6}
print(set1 | set2)
print(set1.union(set2))
反交集 ^ 就是两个集合里面不相交的元素
set1 = {4,5,6,7,8,9} set2 = {1,2,3,4,5,6}
print(set1 ^ set2)
print(set1.symmetric_difference(set2))
差集 -
set1 = {4,5,6,7,8,9} set2 = {1,2,3,4,5,6}
print(set1 - set2)
print(set1.difference(set2))
超集 ,子集
set1 = {4,5,6} set2 = {1,2,3,4,5,6}
print(set1.issubset(set2))
print(set2.issuperset(set1))