>>> a={1,2,3,4,5,6}>>> b={4,5,6,7,8,9}>>> a & b
{4,5,6}
(9) in,not in 判断集合中是否有某一元素
>>> a={1,2,3,4,5,6}>>>0in a
False>>>0notin a
True>>>3in a
True
(10) sum() 返回集合中所有元素之和
>>> a={1,2,3}>>>sum(a)6
3 集合常用的函数
(1) add(elem) 向集合中增加一个元素,如果此元素已经存在于集合中,则不作任何处理
>>> a={1,2,3}>>> a.add(4)>>> a
{1,2,3,4}>>> a.add(1)>>> a
{1,2,3,4}
(2) clear() 清除集合中的所有元素
>>> a={1,2,3}>>> a
{1,2,3}>>> a.clear()>>> a
set()
(3)copy() 返回集合的一个浅拷贝
>>> a={1,2,3,4}>>> b=a.copy()>>> b
{1,2,3,4}
(4)pop() 从集合中弹出一个元素
>>> a={1,2,3,4,5}>>> a
{1,2,3,4,5}>>> b=a.pop()>>> b
1>>> a
{2,3,4,5}
(5)remove(elem) 从集合中去除某元素,若集合中没有此元素则会报错
>>> a={1,2,3,4,5}>>> a.remove(3)>>> a
{1,2,4,5}>>> a.remove(7)
Traceback (most recent call last):
File "<stdin>", line 1,in<module>
KeyError:7
(6)union(set) 计算两个集合的合集,并返回一个新的集合,原来的两个集合没有变化
>>> a={1,2,3,4,5,6}>>> b={3,4,5,6,7,8}>>> a
{1,2,3,4,5,6}>>> b
{3,4,5,6,7,8}>>> c=a.union(b)>>> c
{1,2,3,4,5,6,7,8}>>> a
{1,2,3,4,5,6}>>> b
{3,4,5,6,7,8}
(7)update(set) 将set集合与原集合计算并集,并更新至原集合
>>> a={1,2,3,4,5,6}>>> b={3,4,5,6,7,8}>>> a
{1,2,3,4,5,6}>>> b
{3,4,5,6,7,8}>>> a.update(b)>>> a
{1,2,3,4,5,6,7,8}>>> b
{3,4,5,6,7,8}
(8)difference(set) 计算集合的差集,和“-”运算符一致
>>> a={1,2,3,4,5,6}>>> b={4,5,6,7,8,9}>>> a.difference(b){1,2,3}>>> a
{1,2,3,4,5,6}>>> b
{4,5,6,7,8,9}
(9)difference_update(set) 计算差集,将结果更新至原集合
>>> a={1,2,3,4,5,6}>>> b={4,5,6,7,8,9}>>> a
{1,2,3,4,5,6}>>> b
{4,5,6,7,8,9}>>> a.difference_update(b)>>> a
{1,2,3}>>> b
{4,5,6,7,8,9}
>>> a={1,2,3,4,5,6}>>> b={4,5,6,7,8,9}>>> a
{1,2,3,4,5,6}>>> b
{4,5,6,7,8,9}>>> a.symmetric_difference(b){1,2,3,7,8,9}>>> a
{1,2,3,4,5,6}>>> b
{4,5,6,7,8,9}