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中的元素不能为字典

相关文章

python内存管理机制原理详解

python内存管理机制原理详解

python内存管理机制: 引用计数 垃圾回收 内存池 1. 引用计数 当一个python对象被引用时 其引用计数增加 1 ; 当其不再被变量引用时 引用计数减 1...

详解Python编程中基本的数学计算使用

数 在 Python 中,对数的规定比较简单,基本在小学数学水平即可理解。 那么,做为零基础学习这,也就从计算小学数学题目开始吧。因为从这里开始,数学的基础知识列位肯定过关了。 &g...

Python中shapefile转换geojson的示例

shapefile转换geojson import shapefile import codecs from json import dumps # read the shapefi...

python读写csv文件并增加行列的实例代码

python读写csv文件并增加行列,具体代码如下所示: # -*- coding: utf-8 -*- """ Created on Thu Aug 17 11:28:17 201...

python用插值法绘制平滑曲线

python用插值法绘制平滑曲线

本文实例为大家分享了python用插值法绘制平滑曲线的具体代码,供大家参考,具体内容如下 原图: 平滑处理后: 代码实现如下: # 1. 随机构造数据 import numpy...