gpt4 book ai didi

python - Numpy 向量化 : Find intersection between list and list of lists

转载 作者:行者123 更新时间:2023-12-01 00:53:35 24 4
gpt4 key购买 nike

我正在尝试找到列表和列表列表之间的交集。这可以通过一个简单的 for 循环轻松解决:

def find_intersec(x,y):
result = []

for i in range(len(y)):
if set(x).intersection(set(y[i])):
result.append(y[i])

return(result)

x = [1,2,3,4,5,6]
y = [[1,2,3], [4,5,6], [9,10,11]]



find_intersec(x,y)

如何将上述内容更改为 numpy 矢量化解决方案?我尝试过 numpy.intersect1d() 但没有成功。

最佳答案

你可以有这样的函数:

import numpy as np

def find_intersec_vec(x, y):
y_all = np.concatenate(y)
y_all_in = np.isin(y_all, x)
splits = np.cumsum([0] + [len(lst) for lst in y])
y_in = np.logical_or.reduceat(y_all_in, splits[:-1])
return [lst for lst, isin in zip(y, y_in) if isin]

测试:

x = [1, 2, 3, 4, 5, 6]
y = [[1, 2, 3], [4, 5], [6, 7], [8, 9, 10, 11]]
print(find_intersec(x, y))
# [[1, 2, 3], [4, 5], [6, 7]]
print(find_intersec_vec(x, y))
# [[1, 2, 3], [4, 5], [6, 7]]

关于python - Numpy 向量化 : Find intersection between list and list of lists,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56394093/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com