集合set,常见函数

集合常见操作

>>> a = set()
>>> a = set('abcd')
>>> a
{'a', 'b', 'c', 'd'}
>>> b = set('cdef')
>>> b
{'d', 'f', 'c', 'e'}
>>> a - b
{'a', 'b'}
>>> a | b
{'d', 'c', 'a', 'b', 'f', 'e'}
>>> a & b
{'d', 'c'}
>>> a ^ b
{'a', 'b', 'f', 'e'}
>>>

删除函数:discard、remove、pop的区别

#discard,如果集合包含待删除元素,不报错
>>> set1
{'Taobao', 'Facebook', 'Runoob', 'Google'}
>>> set1.discard('Google')
>>> set1
{'Taobao', 'Facebook', 'Runoob'}

#remove(),如果集合不包含待删除元素,报错
>>> set1 = set(("Google", "Runoob", "Taobao", "Facebook"))
>>> set1.remove("Google")
>>> set1
{'Taobao', 'Facebook', 'Runoob'}
# pop()
>>> set1 = set(("Google", "Runoob", "Taobao", "Facebook"))
>>> set1
{'Taobao', 'Facebook', 'Runoob', 'Google'}
>>> set1.pop()
'Taobao'
>>> set1.pop()
'Facebook'
>>>

添加函数:add、update区别

# add
>>> set1.add("Google")
>>> set1
{'Taobao', 'Facebook', 'Runoob', 'Google'}
# update
>>> set1.update("Baidu")
>>> set1
{'d', 'Runoob', 'Google', 'Taobao', 'a', 'B', 'u', 'i', 'Facebook'}

清空集合:clear

>>> set1
{'Runoob', 'Google'}
>>> set1.clear()
>>> set1
set()

你可能感兴趣的:(集合set,常见函数)