Python3.7.1学习(三)求两个list的差集、并集与交集

在python3.7.1对列表的处理中,会经常使用到Python求两个list的差集、交集与并集的方法。

下面就以实例形式对此加以分析。

# 求两个list的差集、并集与交集
# 一.两个list差集
#
# 如有下面两个数组:

a = [1, 2, 3]

b = [2, 3]
# 想要的结果是[1]
#
# 下面记录一下三种实现方式:
#
# 1. 正常的方式

# ret = []
# for i in a:
# if i not in b:
# ret.append(i)
#
# print(ret)
# 2.简化版

# ret = [i for i in a if i not in b]
# print(ret)
# 3.高级版

# ret = list(set(a) ^ set(b))
# print(ret)
# 4.最终版
# result = list(set(a).difference(set(b))) # a中有而b中没有的 不建议使用
# result2 = list(set(b).difference(set(a))) # b中有而a中没有的 不建议使用

# print(result) 输出结果为[1]
# print(result2) 输出结果为[]


# 二.两个list并集
result = list(set(a).union(set(b)))
print(result)

# 三.两个list交集
result = list(set(a).intersection(set(b)))
print(result)

猜你喜欢

转载自www.cnblogs.com/simpleBlue3/p/10702152.html