python两个 list 获取交集,并集,差集的方法
2015-10-16 16:06
936 查看
有时候,为了需求,需要统计两个 list 之间的交集,并集,差集。查询了一些资料,现在总结在下面:
1. 获取两个list 的交集
#方法一:
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中没有的
1. 获取两个list 的交集
#方法一:
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中没有的
相关文章推荐
- python3.x的print()函数默认参数
- python中os.walk()遍历目录中所有文件
- 解读Python编程中的命名空间与作用域
- Python中的模块导入和读取键盘输入的方法
- <LeetCode><Easy> 165 CompareVersionNumbers
- python中文件OS模块访问函数
- 统计文件字数,并按出现次数打印结果
- R软件中jiebaR包分词和用python中jieba分词以及做关键字提取及LDA模型
- <LeetCode><Easy> 168 Excel Sheet Column Title
- 第四章 python中的面向对象设计
- Python-爬虫初学
- [LeetCode]题解(python):027-Remove Element
- python核心编程 练习题7.5
- [LeetCode]题解(python):026-Remove Duplicates from Sorted Array
- python rodeo遇到的GConf Error问题
- Python2.7的UnicodeEncodeError: ‘ascii’ codec can’t encode 错误
- <LeetCode><Easy> 169 Majority Element
- <LeetCode><Easy> 171 Excel Sheet Column Number
- python selenium expected_conditions使用实例
- 2.Python起步(未完待续)