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

标签 python numpy vectorization

我正在尝试找到列表和列表列表之间的交集。这可以通过一个简单的 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/

相关文章:

python - 连接列表项

python - 箭头的 Matplotlib 图例

python - 如何在 Pandas 中矢量化动态大小的 numpy 数组

r - 给定具有相同列数的向量,如何选择矩阵的元素?

python - 递减范围内的乘积之和

python - 一般维数的多维网格

python - Onnx 模型输入大小与 Opencv 帧大小不同

python - 在python中查找具有稀疏矩阵特定特征值的特征向量

python - 返回既为零又不为零的未屏蔽元素的索引

python - 有没有比使用循环和 iloc 更快的方法在小 Pandas 数据帧上进行整行比较?