在 Python 中求兩個列表的差集(即在 a 中但不在 b 的元素)是常見需求。以下提供三種實作風格,並補充聯集與差集的標準用法。
a = [1, 2, 3] b = [2, 3] # 期望結果:[1]
ret = []
for i in a:
if i not in b:
ret.append(i)
ret = [i for i in a if i not in b]
ret = list(set(a) ^ set(b)) # 對稱差集:屬於 a 或 b 但不同時屬於兩者
站長偏好: 第三種方式語意清晰且效能佳,尤其資料量大時優勢明顯。
print(list(set(a).union(set(b)))) # [1, 2, 3]
# b 有而 a 沒有 print(list(set(b).difference(set(a)))) # [] # a 有而 b 沒有 print(list(set(a).difference(set(b)))) # [1]
提醒: 集合運算會移除重複元素且不保證順序;若需保留順序與重複值,請使用列表推導式或 collections.Counter。