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

from:https://blog.csdn.net/u012412259/article/details/53175473

1. 获取两个list 的交集

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


2. 获取两个list 的并集

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


3. 获取两个 list 的差集

[python]  view plain  copy
  1. print list(set(b).difference(set(a))) # b中有而a中没有的  

你可能感兴趣的:(python)