删除集合元素的几种方式与区别
删除集合元素有以下几种方式:
remove(),pop(),discard(),clear()
集合的用法:
对于集合来讲有几种运算方法:交集、并集、差集、反交集、子集、超集
交集:
1,remove():可以指定删除的元素,如果指定的元素不在集合中会报错
set_s = {1, 2, 3, 4, 5, 6}
set_s.remove(6)
print(set_s)
返回结果:
{1, 2, 3, 4, 5}
set_s.remove(7)
返回结果:
Traceback (most recent call last):
File "E:/pytestcode/listreri.py", line 21, in <module>
set_s.remove(7)
KeyError: 7
2,pop():从集合中随机删除一个元素,并且返回该元素,如果集合为空则会报错
set_a = set()
a = set_a.pop()
返回结果:
Traceback (most recent call last):
File "E:/pytestcode/listreri.py", line 25, in <module>
a = set_a.pop()
KeyError: 'pop from an empty set'
set_s = {1, 2, 3, 4, 5, 6}
a = set_s.pop()
print(set_s,a)
返回结果:
{2, 3, 4, 5, 6} 1
3、discard():和remove一样可以将元素从集合中删除,区别是如果元素不存在则不会报错
set_s = {1, 2, 3, 4, 5, 6}
set_s.discard(7)
返回结果:
不返回任何信息,也不会提示错误
set_s = {1, 2, 3, 4, 5, 6}
set_s.discard(6)
print(set_s)
返回结果:
{1, 2, 3, 4, 5}
4、clear():用于清空集合。
set_s = {1, 2, 3, 4, 5, 6}
set_s.clear()
print(set_s)
返回结果:
set()
交集:可用&或者intersection,输出一个新的集合,包含共同拥有的元素
s1 = {1,2,3,4,5}
s2 = {3,4,5,6,7}
print('交集:',s1 & s2)
print('交集:',s1.intersection(s2))
结果:
交集: {3, 4, 5}
交集: {3, 4, 5}
并集:可用|或者union,输出一个新的集合,包含两个集合中所有的元素(去重)
s1 = {1,2,3,4,5}
s2 = {3,4,5,6,7}
print('并集:',s1 | s2)
print('并集:',s1.union(s2))
结果:
并集: {1, 2, 3, 4, 5, 6, 7}
并集: {1, 2, 3, 4, 5, 6, 7}
差集:可用 - 或者difference,输出一个新的集合,包含前一个集合中除去共有的元素
s1 = {1,2,3,4,5}
s2 = {3,4,5,6,7}
print('差集:',s1 - s2)
print('差集:',s1.difference(s2))
结果:
差集: {1, 2}
差集: {1, 2}
反交集:可用^或者 symmetric_difference,输出一个新的集合,包含两个集合中除去共有的元素后剩余的所有元素
s1 = {1,2,3,4,5}
s2 = {3,4,5,6,7}
print('反交集:',s1 ^ s2)
print('反交集:',s1.symmetric_difference(s2))
结果:
反交集: {1, 2, 6, 7}
反交集: {1, 2, 6, 7}
子集与超集,简单来讲就是一个集合中的元素包含另一个集合中所有的元素,则“大的”集合叫超集,“小的”叫子集
s4 = {1,2,3,4,5}
print(s3.issubset(s4)) #输出为True,s3是s4的子集
print(s4.issuperset(s3))#输出为True,s4是s3的超集
结果:
True
True
使用frozenset(‘集合名’),可以把集合变成不可变集合
s5 = frozenset(s3)
s5.add(5)
print(s5)
结果:
Traceback (most recent call last):
File "E:/pytestcode/listreri.py", line 41, in <module>
s5.add(5)
AttributeError: 'frozenset' object has no attribute 'add'
版权声明:本文为m0_57133702原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。