zsh2270365028的个人博客分享 http://blog.sciencenet.cn/u/zsh2270365028

博文

[转载]Python两个 list 获取交集,并集,差集的方法

已有 10490 次阅读 2021-7-23 11:51 |个人分类:Python|系统分类:科研笔记|文章来源:转载

refer to:

https://blog.csdn.net/qq_43192819/article/details/88982817

python两个 list 获取交集,并集,差集的方法
1. 获取两个list 的交集/

方法一:
a=[2,3,4,5]
b=[2,5,8]
tmp = [j for j in a if j in b] #列表推导式求的两个列表的交集
print(tmp)
方法二:
print(list(set(a).intersection(set(b)))) # #列用集合的取交集方法
方法三:
lst = []
for i in a:
if i in b :
lst.append(i)
print(lst)
2. 获取两个 list 的差集

方法一:
ret = list(set(a)-set(b))
print(ret)
方法二:
print(list(set(b).difference(set(a)))) # b中有而a中没有的
3.并集

方法一:
rets= list(set(a).union(set(b)))
print(rets)
方法二:
print(list(set(b) | (set(a))))
————————————————
版权声明:本文为CSDN博主「柠 檬没我萌」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_43192819/article/details/88982817



 



https://m.sciencenet.cn/blog-587102-1296670.html

上一篇:[转载]python least-squares fitting
下一篇:python hist-bins-左闭右开

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...
扫一扫,分享此博文

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-5-29 17:22

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部