【问题标题】:Finding the index of elements in an array/list based on another list or array根据另一个列表或数组查找数组/列表中元素的索引
【发布时间】:2020-05-22 07:56:24
【问题描述】:

我有两个列表/数组,如果另一个列表中存在相同的数字,我想在一个列表中查找元素的索引。这是一个例子

 list_A = [1,7,9,7,11,1,2,3,6,4,9,0,1]
 list_B = [9,1,7] 
 #output required : [0,1,2,3,5,10,12]

希望使用 numpy 的任何方法

【问题讨论】:

标签: python list numpy numpy-ndarray indices


【解决方案1】:

使用列表理解和enumerate():

>>> list_A = [1,7,9,7,11,1,2,3,6,4,9,0,1]
>>> list_B = [9,1,7]
>>> [i for i, x in enumerate(list_A) if x in list_B]
[0, 1, 2, 3, 5, 10, 12]

使用 numpy:

>>> import numpy as np
>>> np.where(np.isin(list_A, list_B))
(array([ 0,  1,  2,  3,  5, 10, 12], dtype=int64),)

此外,正如@Chris_Rands 指出的那样,我们还可以先将list_B 转换为集合,因为in 对于集合来说是O(1) 而对于列表来说是O(n)。

时间对比:

import random
import numpy as np
import timeit

list_A = [random.randint(0,100000) for _ in range(100000)]
list_B = [random.randint(0,100000) for _ in range(50000)]

array_A = np.array(A)
array_B = np.array(B)

def lists_enumerate(list_A, list_B):
    return [i for i, x in enumerate(list_A) if x in set(list_B)]

def listB_to_set_enumerate(list_A, list_B):
    set_B = set(list_B)
    return [i for i, x in enumerate(list_A) if x in set_B]

def numpy(array_A, array_B):
    return np.where(np.isin(array_A, array_B))

结果:

>>> %timeit lists_enumerate(list_A, list_B)
48.8 s ± 638 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
>>> %timeit listB_to_set_enumerate(list_A, list_B)
11.2 ms ± 856 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
>>> %timeit numpy(array_A, array_B)
23.3 ms ± 167 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

很明显,对于较大的列表,最好的解决方案是在应用枚举之前将 list_B 转换为集合,或者使用 numpy。

【讨论】:

  • 这也很有效,因为您只迭代列表一次。所以,它是O(N)。
  • 先将list_B转换成集合
  • in 操作对于列表来说是 O(N),对于集合来说是 O(1),所以如果两个列表都很大,就会有所不同
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-19
  • 2012-07-06
  • 1970-01-01
  • 2021-05-13
  • 1970-01-01
  • 2012-10-28
  • 1970-01-01
相关资源
最近更新 更多