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

yipeiwu_com5年前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中marshal对象序列化的相关知识

有时候,要把内存中的一个对象持久化保存到磁盘上,或者序列化成二进制流通过网络发送到远程主机上。Python中有很多模块提供了序列化与反序列化的功能,如:marshal, pickle,...

Python3实现定时任务的四种方式

最近做一个小程序开发任务,主要负责后台部分开发;根据项目需求,需要实现三个定时任务: 1>定时更新微信token,需要2小时更新一次; 2>商品定时上线; 3>定时检测...

python中管道用法入门实例

本文实例讲述了python中管道用法。分享给大家供大家参考。具体如下: #!coding=utf-8 import multiprocessing def consumer(pipe...

python读取word文档的方法

本文实例讲述了python读取word文档的方法。分享给大家供大家参考。具体如下: 首先下载安装win32com from win32com import client as wc...

Python中zfill()方法的使用教程

 zfill()方法用零垫串来填充左边宽度。 语法 以下是zfill()方法的语法: str.zfill(width) 参数    ...