Python:快速获取给定的不同列表中列表中所有元素的位置

时间:2022-10-17 04:18:21

I have a list of numbers of length 10, say

比方说,我有一个长度为10的数字列表

L = [1,2,3,4,5,6,7,8,9,0]

Then, I have an matrix of size 35 * 10 which:

然后,我有一个大小为35 * 10的矩阵,其中:

  • L[0] (value 1) can be found in the first column of the matrix
  • L [0](值1)可以在矩阵的第一列中找到
  • L[1] (value 2) can be found in the 2nd column of the matrix
  • L [1](值2)可以在矩阵的第2列中找到
  • etc.
  • 等等

I would like the index for each value in L in the corresponding column in the matrix given.

我想在给定矩阵的相应列中的L中的每个值的索引。

I know how to do this for one value, but if say the list L is very long and the matrix is large, it might be slow, so wondering if there is a faster way of doing this.

我知道如何为一个值执行此操作,但是如果说列表L很长并且矩阵很大,则可能很慢,因此想知道是否有更快的方法来执行此操作。

1 个解决方案

#1


1  

See docs page.

请参阅文档页面。

L = [1,2,3,4,5,6,7,8,9,0]
a = np.random.ranint(0,50,(35,10))

# identify location of value in array that are in L
ix = np.in1d(a.ravel(), L).reshape(a.shape)

Now you just need to determine what to do with your newly-identified indices!

现在您只需要确定如何处理新识别的索引!

By that, I mean you can remove the "bad" values a[ix==False] = np.NAN

这样,我的意思是你可以删除“坏”值a [ix == False] = np.NAN

or operate on the "good" values exclusively a[ix] *= 25

或者仅以[ix] * = 25对“好”值进行操作

#1


1  

See docs page.

请参阅文档页面。

L = [1,2,3,4,5,6,7,8,9,0]
a = np.random.ranint(0,50,(35,10))

# identify location of value in array that are in L
ix = np.in1d(a.ravel(), L).reshape(a.shape)

Now you just need to determine what to do with your newly-identified indices!

现在您只需要确定如何处理新识别的索引!

By that, I mean you can remove the "bad" values a[ix==False] = np.NAN

这样,我的意思是你可以删除“坏”值a [ix == False] = np.NAN

or operate on the "good" values exclusively a[ix] *= 25

或者仅以[ix] * = 25对“好”值进行操作