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

相关文章

pandas 将list切分后存入DataFrame中的实例

如下所示: #-*- coding:utf-8 -*- import random import pandas as pd import numpy as np list=[1,2,...

pytorch+lstm实现的pos示例

学了几天终于大概明白pytorch怎么用了 这个是直接搬运的官方文档的代码 之后会自己试着实现其他nlp的任务 # Author: Robert Guthrie import to...

老生常谈python函数参数的区别(必看篇)

在运用python的过程中,发现当函数参数为list的时候,在函数内部调用list.append()会改变形参,与C/C++的不太一样,查阅相关资料,在这里记录一下。 python中id...

python创建子类的方法分析

本文实例讲述了python创建子类的方法。分享给大家供大家参考,具体如下: 如果你的类没有从任何祖先类派生,可以使用object作为父类的名字。经典类的声明唯一不同之处在于其没有从祖先类...

Python实现将字符串的首字母变为大写,其余都变为小写的方法

利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。 思路:使用capitalize()函数将字符串的首字母转为大写,其余变为小写 L1 = ['A...