在Python中,集合(set)用一对大括号“{}”表示,集合内的个元素用逗号“,”分隔。集合是可变,无序的。集合中的元素不可重复,且只能是不可变类型的数据类型。
1、集合的创建
①直接将集合赋值给变量
>>>a={1,2} >>>a {1, 2} >>>type(a) <class 'set'> >>>a.add(3) #通过add向集合中添加元素 >>>a {1, 2, 3}
②通过set函数将列表、元组等其他可迭代的对象转换为集合
>>>s=set([1,2,3,4,2,3]) >>>s {1, 2, 3, 4} #可以发现自动去除了重复值
2、集合的更新:可以通过update()方法将另一个集合更新到当前集合。
>>>s1={1,2}
>>>s2={3,4}
>>>s3={1,2,4}
>>>s1.update(s2)
>>>s1
{1, 2, 3, 4}
>>>s1.update(s3) #自动去除了重复的元素
>>>s1
{1, 2, 3, 4}
3、因为是无序的数据类型,所以无法用索引取值,但是可以通过遍历访问集合
>>>s={1,2,3,4,'a','b','c'}
>>>for i in s:
... print(i)
...
1
2
3
4
a
c
b
4、集合的删除操作
①可以使用del命令删除整个集合。
②使用集合对象的pop()方法弹出并删除其中一个元素,并返回删除元素,集合为空时报错。
③remove()方法直接删除指定元素,指定元素不存在时报错。
④discard()方法直接删除指定元素,指定元素不存在时不会报错。
⑤clear()方法清空集合。
>>>s={1,2,3,4,'a','b','c'}
>>>s.pop()
1
>>>s
{2, 3, 4, 'a', 'c', 'b'}
>>>s.pop('a') #pop()方法不能指定元素
Traceback (most recent call last):
File "D:\python3102\lib\code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
TypeError: set.pop() takes no arguments (1 given)
>>>s.remove('a')
>>>s
{2, 3, 4, 'c', 'b'}
>>>s.remove('d') #当指定的元素不存在集合中的时候,用remove()方法报错
Traceback (most recent call last):
File "D:\python3102\lib\code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
KeyError: 'd'
>>>s.discard('c')
>>>s
{2, 3, 4, 'b'}
>>>s.discard('d') #当指定的元素不存在集合中的时候,用discard()方法不报错
>>>s
{2, 3, 4, 'b'}
>>>s.clear()
>>>s
set()
>>>del s
>>>s
Traceback (most recent call last):
File "D:\python3102\lib\code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
NameError: name 's' is not defined. Did you mean: 's1'?
5、集合的运算
①交集
求交集:intersection() 求出结果后将结果更新到当前集合:intersection_update()
判断两个集合是否有交集:isdisjoint(),有交集返回false,没有交集返回true.
>>>s1={1,2,3,4,5,6}
>>>s2={2,3,4,7,8,9}
>>>s3={10,11}
>>>s1.intersection(s2)
{2, 3, 4}
>>>s1
{1, 2, 3, 4, 5, 6}
>>>s1.intersection_update(s2)
>>>s1
{2, 3, 4}
>>>s2.isdisjoint(s3)
True
②并集:union()
>>>s1={1,2,3,4,5,6}
>>>s2={2,3,4,7,8,9}
>>>s1.union(s2)
{1, 2, 3, 4, 5, 6, 7, 8, 9}
>>>s1
{1, 2, 3, 4, 5, 6}
③差集
求差集:difference() 求差集后更新到当前集合:difference_update()
>>>s1={1,2,3,4,5,6}
>>>s2={2,3,4,7,8,9}
>>>s1.difference(s2)
{1, 5, 6}
>>>s1
{1, 2, 3, 4, 5, 6}
>>>s1.difference_update(s2)
>>>s1
{1, 5, 6}
④对称差集
求对称差集:symmetric_difference
求对称差集后更新到当前集合:symmetric_difference_update()
>>>s1={1,2,3,4,5,6}
>>>s2={2,3,4,7,8,9}
>>>s1.symmetric_difference(s2)
{1, 5, 6, 7, 8, 9}
⑤判断子集(issubest())、超集(issuperset())
6、集合操作汇总