网站首页 > 技术文章 正文
Python3学习:求两个list的差集、并集与交集
在python3对列表的处理中,会经常使用到Python求两个list的差集、交集与并集的方法。
下面就以实例形式对此加以分析。
一.两个list差集
如有下面两个数组:
a = [1,2,3]
b = [2,3]
想要的结果是[1]
下面记录一下三种实现方式:
1. 正常的方式
ret = []
for i in a:
if i not in b:
ret.append(i)
2.简化版
ret = [ i for i in a if i not in b ]
3.高级版
ret = list(set(a) ^ set(b))
4.最终版
print (list(set(b).difference(set(a)))) # b中有而a中没有的
二.两个list并集
print (list(set(a).union(set(b))))
三.两个list交集
print (list(set(a).intersection(set(b))))
————————————————
猜你喜欢
- 2024-10-16 python数据类型(python数据类型bool)
- 2024-10-16 JavaScript Set、Map、WeakSet 和 WeakMap 的区别?
- 2024-10-16 69-1-10000遗漏了哪些序号#差集#Filter...
- 2024-10-16 进入Python的世界12-常用的程序例子整理二
- 2024-10-16 Java路径-35-Java的HashSet(java路径怎么找)
- 2024-10-16 Redis五种数据类型详解(redis7种数据类型)
- 2024-10-16 那些你不得不知的Redis基础类型常用操作、命令
- 2024-10-16 美团外卖iOS App冷启动治理(美团早启动)
- 2024-10-16 (Python)通过口诀记忆数组、集合、字典、元组
- 2024-10-16 【C++泛型编程】(二)标准模板库 STL
- 最近发表
- 标签列表
-
- cmd/c (57)
- c++中::是什么意思 (57)
- sqlset (59)
- ps可以打开pdf格式吗 (58)
- phprequire_once (61)
- localstorage.removeitem (74)
- routermode (59)
- vector线程安全吗 (70)
- & (66)
- java (73)
- org.redisson (64)
- log.warn (60)
- cannotinstantiatethetype (62)
- js数组插入 (83)
- resttemplateokhttp (59)
- gormwherein (64)
- linux删除一个文件夹 (65)
- mac安装java (72)
- reader.onload (61)
- outofmemoryerror是什么意思 (64)
- flask文件上传 (63)
- eacces (67)
- 查看mysql是否启动 (70)
- java是值传递还是引用传递 (58)
- 无效的列索引 (74)