Dynadot Jtti 搬瓦工 腾讯云

Python List、Set 的交集、并集、差集操作

GigsGigsCloud

本文整理一下 Python 中 list、set 等的交集、并集、差集操作,整理一下方便自己后续使用,也当做一个记录。

一、Python List 交集、并集、差集

1). 获取两个list 的交集

方法一:

a = [2,3,4,5]
b = [2,5,8]
tmp = [val for val in a if val in b]
print tmp
#[2, 5]

方法二:

print list(set(a).intersection(set(b)))

2). 获取两个list 的并集

print list(set(a).union(set(b)))

3). 获取两个 list 的差集

print list(set(b).difference(set(a))) # b中有而a中没有的

二、Python Set 交集、并集、差集

s = set([3,5,9,10,20,40])      #创建一个数值集合
t = set([3,5,9,1,7,29,81])      #创建一个数值集合
a = t | s          # t 和 s的并集 ,等价于t.union(s)
b = t & s          # t 和 s的交集 ,等价于t.intersection(s)
c = t - s          # 求差集(项在t中,但不在s中)  ,等价于t.difference(s)
d = t ^ s          # 对称差集(项在t或s中,但不会同时出现在二者中),等价于t.symmetric_difference(s)

原文链接:https://www.cnblogs.com/DjangoBlog/p/3510385.html

Dynadot Hostwinds
赞(1)
版权声明:本文采用知识共享 署名4.0国际许可协议 [BY-NC-SA] 进行授权
文章名称:《Python List、Set 的交集、并集、差集操作
文章链接:https://oldtang.com/2507.html
本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。