python 取两/多个list的交集

python 取两个/多个list的交集

Two List

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]

1、自定义def Method

def intersection(lst1, lst2): 
    lst3 = [value for value in lst1 if value in lst2] 
    return lst3 

2、set() Method

def intersection(lst1, lst2): 
    return list(set(lst1) & set(lst2)) 

3、内置函数intersection()

set(lst1).intersection(lst2)

4、np内置函数

import numpy as np
np.intersect1d(lst1,lst2)

5、混合方法将时间复杂度降至O(n)

def intersection(lst1, lst2): 
    temp = set(lst2) 
    lst3 = [value for value in lst1 if value in temp] 
    return lst3 

6、一对多:filter()方法

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)) 

Multiple Lists

1、set() && intersection() 内置函数

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))

2、多对多:map 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

你可能感兴趣的:(Data,Processing,python)