溫馨提示×

Python兩個列表取交集的方法是什么

小億
267
2023-12-14 18:22:24
欄目: 編程語言

Python中兩個列表取交集的方法有幾種,以下是常見的幾種方法:

  1. 使用set()函數:將兩個列表轉換為集合,然后使用交集操作符&獲取交集元素,最后將結果轉換回列表。
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
intersection = list(set(list1) & set(list2))
print(intersection)  # 輸出:[4, 5]
  1. 使用列表推導式:遍歷一個列表,判斷該元素是否同時存在于另一個列表中,如果是則保留該元素。
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
intersection = [x for x in list1 if x in list2]
print(intersection)  # 輸出:[4, 5]
  1. 使用內置函數filter():使用filter()函數篩選出同時存在于兩個列表中的元素,然后將結果轉換為列表。
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
intersection = list(filter(lambda x: x in list2, list1))
print(intersection)  # 輸出:[4, 5]

這些方法都可以實現兩個列表的交集操作,選擇哪種方法取決于個人的偏好和具體的需求。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女