python集合的操作

1. 获取两个list 的交集

[python] view plain copy
 
 print?
  1. # -*- coding=utf-8 -*-  
  2.   
  3. #方法一:  
  4. a=[2,3,4,5]  
  5. b=[2,5,8]  
  6. tmp = [val for val in a if val in b]  
  7. print tmp  
  8. #[2, 5]  
  9.   
  10. #方法二  
  11. print list(set(a).intersection(set(b)))  


2. 获取两个list 的并集

[python] view plain copy
 
 print?
  1. print list(set(a).union(set(b)))  


3. 获取两个list 的差集

[python] view plain copy
 
 print?
  1. print list(set(b).difference(set(a))) # b中有而a中没有的  
  2. print list(set(a).difference(set(b))) # a中有而b中没有的
posted @ 2017-09-23 17:21  dabaohaomenga  阅读(168)  评论(0编辑  收藏  举报