python set集合运算(交集,并集,差集,对称差集)
2023-09-11 14:14:27 时间
python set集合运算(交集,并集,差集,对称差集)
1》交集
>>> x={1,2,3,4}
>>> y={3,4,5,6}
>>> x
set([1, 2, 3, 4])
>>> y
set([3, 4, 5, 6])
>>> x&y
set([3, 4])
>>> x.intersection(y)
set([3, 4])
2》并集
>>> x | y #集合并集
set([1, 2, 3, 4, 5, 6])
>>> x.union(y)
set([1, 2, 3, 4, 5, 6])
3》差集
>>> x-y # x与y的差集
set([1, 2])
>>> x.difference(y)# x与y的差集
set([1, 2])
>>> y-x # y与x的差集
set([5, 6])
>>> y.difference(x)# y与x的差集
set([5, 6])
4》对称差集
>>> x^y
set([1, 2, 5, 6])
>>> y^x
set([1, 2, 5, 6])
>>> x.symmetric_difference(y)
set([1, 2, 5, 6])
>>> y.symmetric_difference(x)
set([1, 2, 5, 6])
5》集合的子集和超集
>>> x
set([1, 2, 3, 4])
>>> z
set([1, 2, 3])
>>> z.issubset(x)#z是x的子集
True
>>> x.issuperset(z)#x是z的超集
True
下面的图片形象地展示了set集合的各种运算:
集合 x <==> ① + ②
集合 x <==> ② + ③
交集 x&6 <==> ②
并集 x|y <==> ① + ② + ③
差集 x-y <==> ①
差集 y-x <==> ③
对称差集 x^y == y^x <==> ① + ③
相关文章
- python魔法方法之-Python __repr__()方法:显示属性
- python 保存图片_用Python从视频中提取每一帧的图片
- 【Python】ValueError: unsupported pickle protocol: 5解决方案/同一个项目 python环境尽量保持一致
- Python脚本生成sitemap
- 选择一个 Python Web 框架:Django vs Flask vs Pyramid
- Python集合(set)的操作方法汇总(约20种操作方法),并附示例代码
- Python中python-nmap模块的使用
- 【Python】解析浏览器中的header请求头为JSON格式
- Python面向对象编程 - 一个记事本程序范例(二)
- Python使用pyMysql模块插入数据到mysql的乱码解决
- python通过snmp协议运用多线程获取多台主机网卡信息,写入数据库
- 【Python分布式服务框架】python实现gRPC服务
- Python实例---CRM管理系统分析180331
- 用Python编写博客导出工具
- Python 基础 之 python 中 进程、线程、协程对比 区别和联系
- 【爬虫系列】【Python】python with as的用法
- python爬虫之selenium+BeautifulSoup库,爬取搜索内容并保存excel
- 【Linux学习笔记】解决:yum install python-dev 报错(CentOS安装Python-dev库)
- [Python] set()函数