- 对于 3M 元素容器,此答案比接受的答案快
67.2 times。
- 这可以使用
numpy 来完成,方法是将list 转换为numpy.array。
- 他的答案代码是对Find index where elements change value numpy 代码的修改。
- 该问题需要所有转换
v[:-1] != v[1:],而不仅仅是小到大的转换,v[:-1] < v[1:],在这个问题中。
- 创建一个布尔数组,将数组与自身进行比较,并移动一位。
- 使用
np.where 返回True 的索引
- 这会找到更改前的索引,因为数组被移位进行比较,所以使用
+1得到正确的值。
import numpy as np
v = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0]
# convert to array
v = np.array(v)
# create a Boolean array
map = v[:-1] < v[1:]
# return the indices
idx = np.where(map)[0] + 1
print(idx)
[out]:
array([ 7, 24], dtype=int64)
%timeit
# v is 3M elements
v = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0] * 100000
# accepted answer
%timeit [i for i,m in enumerate(v) if i and m and not v[i-1]]
[out]:
336 ms ± 14 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
# this answer
v = np.array(v)
%timeit np.where(v[:-1] < v[1:])[0] + 1
[out]:
5.03 ms ± 85.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)