python获得两个数组的交集、并集、差集的代码

下面的内容段是关于python获得两个数组的交集、并集、差集的内容,应该是对码农们有较大用途。

#方法一:
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中没有的

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

猜你喜欢

转载自blog.csdn.net/weixin_43947759/article/details/88915384
今日推荐