在本教程中,我們將討論如何獲得這兩個列表的交集。兩個列表的交集意味着我們需要獲得兩個初始列表的所有熟悉元素。
Python 以其出色的內置數據結構而聞名。 Python 列表是 Python 著名且有價值的內置數據類型之一。它可以按排序順序存儲各種數據類型值。但是像集合這樣的列表沒有內置功能。
Python 提供了許多方法來執行列表的交集。讓我們看看下面的場景。
輸入:
list1 = [40, 90, 11, 58, 31, 66, 28, 54, 79]
list2 = [58, 90, 54, 31, 45, 11, 66, 28, 26]
輸出:
[90, 11, 58, 31, 66, 28, 54]
輸入:
list1 = [4, 9, 1, 17, 11, 26, 28, 54, 69]
list2 = [9, 9, 74, 21, 45, 11, 63, 28, 26]
輸出:
[9, 11, 26, 28]
讓我們看看下面的方法來獲得兩個列表的交集。
方法 1:用於循環
# Python program to get the intersection
# of two lists in most simple way
def intersection_list(list1, list2):
list3 = [value for value in list1 if value in list2]
return list3
# Driver Code
list1 = [40, 90, 11, 58, 31, 66, 28, 54, 79]
list2 = [58, 90, 54, 31, 45, 11, 66, 28, 26]
print(intersection_list(list1, list2))
輸出:
[90, 11, 58, 31, 66, 28, 54]
我們使用 for
循環從兩個列表中獲取公共值,並將其存儲在 list3 變量中。
方法 2:將列錶轉換為集合
def intersection_list(list1, list2):
return list(set(list1) & set(list2))
list1 = [40, 90, 11, 58, 31, 66, 28, 54, 79]
list2 = [58, 90, 54, 31, 45, 11, 66, 28, 26]
print(intersection_list(list1, list2))
輸出:
[66, 90, 11, 54, 58, 28, 31]
方法 3:
我們將使用內置集的交集()方法。路口()是集合中的一流部分。讓我們理解下面的例子。
示例-
# Python program to get the intersection
# of two lists using set() and intersection()
def intersection_list(list1, list2):
return set(list1).intersection(list2)
list1 = [40, 90, 11, 58, 31, 66, 28, 54, 79]
list2 = [58, 90, 54, 31, 45, 11, 66, 28, 26]
print(intersection_list(list1, list2))
輸出:
{66, 90, 11, 54, 58, 28, 31}
方法 4:
在這個方法中,我們將使用混合方法。這是執行任務的有效方法。讓我們理解下面的例子。
示例-
# Python program to get the intersection
# of two lists
def intersection(list1, list2):
# Use of hybrid method
temp = set(list2)
list3 = [value for value in list1 if value in temp]
return list3
list1 = [40, 90, 11, 58, 31, 66, 28, 54, 79]
list2 = [58, 90, 54, 31, 45, 11, 66, 28, 26]
print(intersection(list1, list2))
輸出:
[90, 11, 58, 31, 66, 28, 54]
方法 5:
在這個方法中,我們將使用濾鏡()方法。交集在其他列表內的子列表上執行。讓我們理解下面的例子。
示例-
# Python program togetthe intersection
# of two lists, sublists and use of filter()
def intersection_list(list1, list2):
list3 = [list(filter(lambda x: x in list1, sublist)) for sublist in list2]
return list3
list1 = [10, 9, 17, 40, 23, 18, 56, 49, 58, 60]
list2 = [[25, 17, 23, 40, 32], [1, 10, 13, 27, 28], [60, 55, 61, 78, 15, 76]]
print(intersection_list(list1, list2))
輸出:
[[17, 23, 40], [10], [60]]
filter() 方法獲取子列表的每個項目,並檢查它是否存在於列表 1 中。對列表 2 中的每個子列表執行列表推導。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/291025.html