集合set常用的方法
方法 | 意义 |
---|---|
S.add(e) | 在集合中添加一个新的元素e;如果元素已经存在,则不添加 |
S.remove(e) | 从集合中删除一个元素,如果元素不存在于集合中,则会产生一个KeyError错误 |
S.discard(e) | 从集合S中移除一个元素e,在元素e不存在时什么都不做; |
S.clear() | 清空集合内的所有元素 |
S.copy() | 将集合进行一次浅拷贝 |
S.pop() | 从集合S中删除一个随机元素;如果此集合为空,则引发KeyError异常 |
S.update(s2) | 等同于 S |
举例说明:
add的用法
>>> s = {1,2,3}
>>> s.add(1)
>>> s
{1, 2, 3}
>>> s.add(4)
>>> s
{1, 2, 3, 4}
添加新元素,如果集合里已经有了则什么都不添加,如果没有,则添加该元素
remove的用法
>>> s = {1, 2, 3, 4}
>>> s.remove(1)
>>> s
{2, 3, 4}
>>> s.remove(100) # 集合中没有的话会报错
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
s.remove(100)
KeyError: 100
discard(e)的用法
>>> s = {2, 3, 4}
>>> s.discard(2)
>>> s
{3, 4}
>>> s.discard(100) # 同remove不同,如果不存在也不会报错,只是什么也不执行
>>> s
{3, 4}
pop()的用法
>>> s = {3, 4}
>>> s.pop() # 随机移除一个元素
3
>>> s
{4}
>>> s.pop(100) # 集合是无序的,不需要索引值
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
s.pop(100)
TypeError: pop() takes no arguments (1 given)
>>> s = set()
>>> s.pop() # 集合为空的话使用pop会报错
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
s.pop()
KeyError: 'pop from an empty set'
本节完