在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)