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

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值