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