1.基础模块-set
向 set 集合中添加元素
setname.add(element)
需要注意的是,使用 add() 方法添加的元素,只能是数字、字符串、元组或者布尔类型(True 和 False)值,不能添加列表、字典、集合这类可变的数据,否则 Python 解释器会报 TypeError 错误。例如:
a = {1,2,3}
a.add((1,2))
print(a)
a.add([1,2])
print(a)
运行结果为:
{(1, 2), 1, 2, 3}
Traceback (most recent call last):
File "C:\Users\mengma\Desktop\1.py", line 4, in <module>
a.add([1,2])
TypeError: unhashable type: 'list'
Python set集合运算
交集 & 取两集合公共的元素 >>> set1 & set2
{3}
并集 | 取两集合全部的元素 >>> set1 | set2
{1,2,3,4,5}
差集 - 取一个集合中另一集合没有的元素 >>> set1 - set2
{1,2}
>>> set2 - set1
{4,5}
对称差集 ^