Python 数据类型-集合
集合也是Python数据类型之一。接下来主要介绍集合类型的操作。
1.创建集合
#!/usr/bin/env python # -*- coding:utf-8 -*- #创建集合 jh0101={11,22,"lucy",(1,"sdf")} print(jh0101) print(type(jh0101))View Code
代码运行结果:
{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)View Code
代码运行结果:
{'asdf', ('dsdf', '12we', 11), 22}
3.列表转换为集合
#!/usr/bin/env python # -*- coding:utf-8 -*- #列表转换为集合 jh01 = set(["qwe", 123]) print(jh01) print(type(jh01))View Code
代码运行结果:
{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)View Code
代码运行结果:
{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)View Code
代码运行结果:
{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)View Code
代码运行结果:
{11, 13}
{11, 13}