python list间的并集、差集与交集

一.两个list差集

如有下面两个数组:

a = [1,2,3]

b = [2,3]

想要的结果是[1]

下面记录一下三种实现方式:

1. 正常的方式

  1.  
    ret = []
  2.  
    for i in a:
  3.  
    if i not in b:
  4.  
    ret.append(i)

2.简化版

ret = [ i for i in a if i not in b ]

3.高级版

ret = list(set(a) ^ set(b))

4.最终版

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

二.两个list并集

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

三.两个list交集

print (list(set(a).intersection(set(b))))
 
原文地址:https://www.cnblogs.com/kwzblog/p/14101262.html