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

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

WBOY
Release: 2016-06-06 11:23:07
Original
2425 people have browsed it

本文实例讲述了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)))
Copy after login

2. 获取两个list 的并集

print list(set(a).union(set(b)))
Copy after login

3. 获取两个 list 的差集

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

通过以上方法,就能处理python list 的交集,并集,差集了。

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template