Python 数据类型-集合
集合也是Python数据类型之一。接下来主要介绍集合类型的操作。
1.创建集合
#!/usr/bin/env python # -*- coding:utf-8 -*- #创建集合 jh0101={11,22,"lucy",(1,"sdf")} print(jh0101) print(type(jh0101))
代码运行结果:
{11, 'lucy', (1, 'sdf'), 22}
<class 'set'>
2.求交集
#!/usr/bin/env python # -*- coding:utf-8 -*- #求交集 jh01={22,333,"asdf",("dsdf","12we",11)} jh02={22,"asdf",("dsdf","12we",11)} jiaoji=jh02.intersection(jh01) print(jiaoji)
代码运行结果:
{'asdf', ('dsdf', '12we', 11), 22}
3.列表转换为集合
#!/usr/bin/env python # -*- coding:utf-8 -*- #列表转换为集合 jh01 = set(["qwe", 123]) print(jh01) print(type(jh01))
代码运行结果:
{123, 'qwe'}
<class 'set'>
4.求并集
#!/usr/bin/env python # -*- coding:utf-8 -*- #求并集 jh01={11,22,333} jh02={333,13,22} bj=jh01.union(jh02) print(bj)
代码运行结果:
{13, 22, 11, 333}
5.求差集
#!/usr/bin/env python # -*- coding:utf-8 -*- #求差集 jh01={11,22,333} jh02={333,13,22} cj01=jh02.difference(jh01) print(cj01) cj02=jh01.difference(jh02) print(cj02)
代码运行结果:
{13}
{11}
6.求交叉补集
#!/usr/bin/env python # -*- coding:utf-8 -*- #求交叉补集 jh01={11,22,333} jh02={333,13,22} jcbj01=jh01.symmetric_difference(jh02) print(jcbj01) jcbj02=jh02.symmetric_difference(jh01) print(jcbj02)
代码运行结果:
{11, 13}
{11, 13}
7.向集合中添加元素/浅复制/随机删除集合中的某个元素/清空集合
#!/usr/bin/env python # -*- coding:utf-8 -*- jh01={11,22,"dfre",(22,"dfgh","g",)} print(jh01) jh01.add("mb1222") print(jh01) qiancopy=jh01.copy() print(qiancopy) suijishan=jh01.pop() print(jh01) jh01.clear() print(jh01)
代码运行结果:
{'dfre', 11, (22, 'dfgh', 'g'), 22}
{'dfre', 11, 'mb1222', (22, 'dfgh', 'g'), 22}
{'dfre', 11, 'mb1222', (22, 'dfgh', 'g'), 22}
{11, 'mb1222', (22, 'dfgh', 'g'), 22}
set()
8.删除集合指定元素,被删除的元素不存在会报错
#!/usr/bin/env python # -*- coding:utf-8 -*- #指定删除集合中某个元素,被删除的元素不存在会报错 jh01={11,22,333,"hello",(11,22,333,)} jh01.remove("hellodddd") print(jh01)
代码运行结果:
C:\Users\Administrator\PycharmProjects\python_s3\venv\Scripts\python.exe C:/Users/Administrator/PycharmProjects/python_s3/day10/s02.py
Traceback (most recent call last):
File "C:/Users/Administrator/PycharmProjects/python_s3/day10/s02.py", line 6, in <module>
jh01.remove("hellodddd")
KeyError: 'hellodddd'
9.删除集合指定元素,被删除的元素不存在不会报错
#!/usr/bin/env python # -*- coding:utf-8 -*- #指定删除集合中某个元素,被删除的元素不存在不会报错 jh01={11,22,333,"hello",(11,22,333,)} jh01.discard(222) print(jh01)
代码运行结果:
{11, 'hello', 333, 22, (11, 22, 333)}