python两个 list 获取交集,并集,差集的方法

来源:互联网 发布:程序员笔记本对cpu 编辑:程序博客网 时间:2024/05/21 07:49

转自:

http://blog.chinaunix.net/uid-200142-id-3992553.html


有时候,为了需求,需要统计两个 list 之间的交集,并集,差集。查询了一些资料,现在总结在下面:
1. 获取两个list 的交集

  1. #方法一:
  2. a=[2,3,4,5]
  3. b=[2,5,8]
  4. tmp = [valfor val in aif val in b]
  5. print tmp
  6. #[2, 5]

  7. #方法二
  8. print list(set(a).intersection(set(b)))

2. 获取两个list 的并集

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

3. 获取两个 list 的差集

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

0 0