如何在纽比中做到这一点:谢谢!在
输入:
A = np.array([0, 1, 2, 3])
B = np.array([[3, 2, 0], [0, 2, 1], [2, 3, 1], [3, 0, 1]])
输出:
^{pr2}$在Python中:
A = np.array([0 ,1 ,2 ,3])
B = np.array([[3 ,2 ,0], [0 ,2 ,1], [2 ,3 ,1], [3 ,0 ,1]])
result = []
for x , valA in enumerate (A) :
inArray = []
for y , valB in enumerate (B) :
if valA in valB:
inArray.append (y)
result.append (inArray)
print result
# result = [[0, 1, 3], [1, 2, 3], [0, 1, 2], [0, 2, 3]]
方法1
下面是一个使用^{} -
方法2
假设}可以被视为按行保存列索引。一旦与}值。这应该更节省内存。在
A
和B
都是正数,我们可以考虑它们来表示2D
网格上的索引,这样{B
对应的2D
网格就位,我们只需要考虑与A
相交的列。最后,我们得到这样一个2D
网格中True
值的索引,从而给出R
和{因此,另一种方法应该是这样的-
^{pr2}$样本运行-
运行时测试
按
100x
放大数据集大小,下面是一个快速的运行时测试结果-性能进一步提升!
或者,我们可以在第二种方法中以一种转置的方式创建
2D
网格。这个想法是为了避免R,C = np.where(mask.T)
中的转置,这似乎是一个瓶颈。因此,第二种方法的修改版本和相关的运行时将如下所示-组合了
numpy
和list-comprehension
的选项:相关问题 更多 >
编程相关推荐