set函数生成的是一个无序不重复的元素集,基本功能为关系测试和消除重复元素。集合对象还支持union(联合), intersection(交), difference(差)和sysmmetric difference(对称差集)等数学运算。
例如:
消除重复值:
a = [1, 2, 3, 4, 5, 6, 2, 4, 2, 1, 5, 3, 2]
b = set(a)
print(b)
>>{1, 2, 3, 4, 5, 6}
交集:
x = set([1, 4, 5, 2, 3])
y = set([1, 6, 3, 8])
z = x&y
>>z={1, 3}
并集:
x = set([1, 4, 5, 2, 3])
y = set([1, 6, 3, 8])
z = x|y
>>z={1, 2, 3, 4, 5, 6, 8}
差集:
x = set([1, 4, 5, 2, 3])
y = set([1, 6, 3, 8])
z = x-y
>>z={2, 4, 5}