Python集合的常用方法:
集合特性:无序的、不重复的元素序列
注意:不支持+、*
一、增加:.add()
① .add()
用法:在集合中添加一个元素,如果元素已经存在,则不添加
示例:set1 = {1,2,3,4,5}
set1.add(6)
print(set1)
结果:{1, 2, 3, 4, 5, 6}
二、删除:.remove()、.pop()、.discard()、.clear()
① .remove()
用法:从集合中删除一个元素,如果元素不存在于集合中,则会报错KeyError
示例:set1 = {1,2,3,4,5}
set1.remove(1)
print(set1)
结果:{2, 3, 4, 5}
② .pop()
用法:从集合中删除一个随机元素(默认删除第一个);如果集合为空,则会报错KeyError
示例:set1 = {1,2,3,4,5}
set1.pop()
print(set1)
结果:{2,3,4,5}
③ .discard()
用法:从集合中移除一个元素,如果不存在该元素,则不会报错
示例:set1 = {1,2,3,4,5}
set1.discard(6)
print(set1)
结果:{1,2,3,4,5}
④ .clear()
用法:清空集合内的所有元素
示例:set1 = {1,2,3,4,5}
set1.clear()
print(set1)
结果:set()
三、更新:.update() ---并集
① S.update(s2)
用法:用S与s2得到的全集更新变量S
示例:set1 = {1,2,3,4,5,6}
set2 = {6,7}
set1.update(set2)
print(set1)
结果:{1, 2, 3, 4, 5, 6, 7}
四、合并:|、.union() ---并集
① |
用法:将两个集合合并成一个新的集合,取并集
示例:set1 = {1,2,3,4,5,6}
set2 = {6,7}
result = set1 | set2
print(result)
结果:{1, 2, 3, 4, 5, 6, 7}
② .union()
用法:将两个集合合并成一个新的集合,取并集
示例:set1 = {1,2,3,4,5,6}
set2 = {6,7,8}
result = set1.union(set2)
print(result)
结果:{1, 2, 3, 4, 5, 6, 7, 8}
五、交集:&、S.intersection(s2)、S.intersection_update(s2)
① &
用法:取交集
示例:set1 = {1,2,3,4,5,6}
set2 = {5,6,7}
result = set1 & set2
print(result)
结果:{5,6}
② S.intersection(s2)
示例:set1 = {1,2,3,4,5,6}
set2 = {5,6,7}
result = set1.intersection(set2)
print(result)
结果:{5,6}
③ S.intersection_update(s2)
示例:set1 = {1,2,3,4,5,6}
set2 = {5,6,7}
set1.intersection_update(set2)
print(set1)
结果:{5,6}
六、差集:-、S.diffrence(s2)、S.difference_update(s2)
① -
示例:set1 = {1,2,3,4,5}
set2 = {5,6}
result = set1 - set2
print(result)
结果:{1,2,3,4}
② S.difference(s2)
示例:set1 = {1,2,3,4,5}
set2 = {5,6}
result = set1.difference(set2)
print(result)
结果:{1,2,3,4}
③ S.difference_update(s2)
示例:set1 = {1,2,3,4,5}
set2 = {5,6}
set1.difference_update(set2)
print(set1)
结果:{1,2,3,4}
七、对称补集:^、S.symmetric_difference(s2)、S.symmetric_difference_update(s2)
① ^
示例:set1 = {1,2,3,4,5}
set2 = {5,6,7}
result = set1 ^ set2
print(result)
结果:{1,2,3,4,6,7}
② S.symmetric_difference(s2)
示例:set1 = {1,2,3,4,5}
set2 = {5,6,7}
result = set1.symmetric_difference(set2)
print(result)
结果:{1,2,3,4,6,7}
③ S.symmetric_difference_update(s2)
示例:set1 = {1,2,3,4,5}
set2 = {5,6,7}
set1.symmetric_difference_update(set2)
print(set1)
结果:{1,2,3,4,6,7}
八、判断:S.isdisjoint(s2)、S.issubset(s2)、S.issuperset()
① S.isdisjoint(s2)
用法:如果S与s2交集为空,返回True,非空返回False
示例:set1 = {1,2,3,4,5}
set2 = {6,7}
result = set1.isdisjoint(set2)
print(result)
结果:True
② S.issubset(s2)
用法:如果S是s2的子集,返回True,否则返回False
示例:set1 = {1,2,3,4,5,6,7}
set2 = {6,7}
result = set1.issubset(set2)
print(result)
结果:False
③ S.issuperset(s2)
用法:如果S是s2的父集,则返回True,否则返回False
示例:set1 = {1,2,3,4,5,6,7}
set2 = {6,7}
result = set1.issuperset(set2)
print(result)
结果:True