Home >Backend Development >Python Tutorial >python获得两个数组交集、并集、差集的方法

python获得两个数组交集、并集、差集的方法

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-06 11:23:072436browse

本文实例讲述了python获得两个数组交集、并集、差集的房部分。分享给大家供大家参考。具体如下:

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 list 的交集,并集,差集了。

希望本文所述对大家的Python程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn