Input:
lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]
lst2 = [9, 4, 5, 36, 47, 26, 10, 45, 87]
Expected Output:
[9,10,4,5]
def intersection(lst1, lst2):
lst3 = [value for value in lst1 if value in lst2]
return lst3
def intersection(lst1, lst2):
return list(set(lst1) & set(lst2))
set(lst1).intersection(lst2)
import numpy as np
np.intersect1d(lst1,lst2)
def intersection(lst1, lst2):
temp = set(lst2)
lst3 = [value for value in lst1 if value in temp]
return lst3
lst1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
lst2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
def intersection(lst1, lst2):
# filter(lambda x: x in arr1, arr2)-->
# filter element x from list arr2 where x also lies in arr1
lst3 = [list(filter(lambda x: x in lst1, sublist)) for sublist in lst2]
return lst3
print(intersection(lst1, lst2))
Input:
all_list = [[1,2,3,4], [2,3,4], [3,4,5,6,7]]
Expected Output:
{3,4}
内循环找交集
set.intersection(*map(set,all_list))
Input :
lst1 = [['a', 'c'], ['d', 'e']]
lst2 = [['a', 'c'], ['e', 'f'], ['d', 'e']]
Output :
[['a', 'c'], ['d', 'e']]
def intersection(lst1, lst2):
tup1 = map(tuple, lst1)
tup2 = map(tuple, lst2)
return list(map(list, set(tup1).intersection(tup2)))
参考引用
Python | Intersection of two lists
Python | Intersection of multiple lists