Python 两个列表的差集、并集和交集实现代码

yipeiwu_com6年前Python基础

①差集
方法一:

if __name__ == '__main__':
	a_list = [{'a' : 1}, {'b' : 2}, {'c' : 3}, {'d' : 4}, {'e' : 5}]
	b_list = [{'a' : 1}, {'b' : 2}]
	ret_list = []
	for item in a_list:
		if item not in b_list:
			ret_list.append(item)
	for item in b_list:
		if item not in a_list:
			ret_list.append(item)
	print(ret_list)

执行结果:

方法二:

if __name__ == '__main__':
	a_list = [{'a' : 1}, {'b' : 2}, {'c' : 3}, {'d' : 4}, {'e' : 5}]
	b_list = [{'a' : 1}, {'b' : 2}]
	ret_list = [item for item in a_list if item not in b_list] + [item for item in b_list if item not in a_list]
	print(ret_list)

执行结果:

方法三:

if __name__ == '__main__':
	a_list = [1, 2, 3, 4, 5]
	b_list = [1, 4, 5]
	ret_list = list(set(a_list)^set(b_list))
	print(ret_list)

执行结果:

注:此方法中,两个list中的元素不能为字典

②并集

if __name__ == '__main__':
	a_list = [1, 2, 3, 4, 5]
	b_list = [1, 4, 5]
	ret_list = list(set(a_list).union(set(b_list)))
	print(ret_list)

执行结果:

注:此方法中,两个list中的元素不能为字典

③交集

if __name__ == '__main__':
	a_list = [1, 2, 3, 4, 5]
	b_list = [1, 4, 5]
	ret_list = list((set(a_list).union(set(b_list)))^(set(a_list)^set(b_list)))
	print(ret_list)

执行结果:

注:此方法中,两个list中的元素不能为字典

相关文章

Windows系统下PhantomJS的安装和基本用法

Windows系统下PhantomJS的安装和基本用法

1.安装 下载网址:http://phantomjs.org/download.html 选择合适的版本。然后解压即可。 环境变量的配置: 进入解压的路径: 例如我是解压在D:\Py...

Python OOP类中的几种函数或方法总结

概述 实例方法 使用实例调用时,默认传递实例本身到实例方法的第一个参数self 使用类调用时,必须传递一个实例对象到实例方法的第一个参数 静态方法 使用实例调用和类调用...

django 外键model的互相读取方法

先设定一个关系模型如下: from django.db import models class Blog(models.Model): name = models.CharFiel...

Python 专题六 局部变量、全局变量global、导入模块变量

Python 专题六 局部变量、全局变量global、导入模块变量

定义在函数内的变量有局部作用域,在一个模块中最高级别的变量有全局作用域。本文主要讲述全局变量、局部变量和导入模块变量的方法。 参考:《Python核心编程 (第二版)》 一. 局部变量...

用Python实现大文本文件切割的方法

在实际工作中,有些场景下,因为产品既有功能限制,不支持特大文件的直接处理,需要把大文件进行切割处理。 当然可以通过UltraEdit编辑工具,或者从网上下载一些文件切割器之类的。但这些要...