Python - 多個列表的交集
在本文中,我們將瞭解如何以不同的方式求多個列表的交集。讓我們從傳統的方式開始。
遵循以下步驟解決問題
- 初始化兩個包含多個列表的列表
- 遍歷第一個列表,並在當前專案在第二個列表中也存在時,將其新增到新列表中。
- 列印結果。
示例
# initializing the lists list_1 = [[1, 2], [3, 4], [5, 6]] list_2 = [[3, 4]] # finding the common items from both lists result = [sub_list for sub_list in list_1 if sub_list in list_2] # printing the result print(result)
如果您執行以上程式碼,則可以得到以下結果。
輸出
[[3, 4]]
我們使用集合來求兩個列表的交集。遵循以下步驟。
- 使用 map 將兩個列表項轉換為元組。
- 使用交集和 map 方法求兩個集合的交集。
- 將結果轉換為列表
- 列印結果。
示例
# initializing the lists list_1 = [[1, 2], [3, 4], [5, 6]] list_2 = [[3, 4]] # converting each sub list to tuple for set support tuple_1 = map(tuple, list_1) tuple_2 = map(tuple, list_2) # itersection result = list(map(list, set(tuple_1).intersection(tuple_2))) # printing the result print(result)
如果您執行以上程式碼,則可以得到以下結果。
輸出
[[3, 4]]
結論
如果您對本文有任何疑問,請在評論部分註明。
廣告