我想使用 python 获取列表中数据的边框 例如我有这个列表:
a = [1,1,1,1,4,4,4,6,6,6,6,6,1,1,1]
我想要一个返回数据边框的代码。例如:
a = [1,1,1,1,4,4,4,6,6,6,6,6,1,1,1]
^ ^ ^ ^
b = get_border_index(a)
print(b)
输出:
[0,4,7,12]
如何实现 get_border_index(lst: list) -> list
函数?
最佳答案
也适用于非常长的列表或数组的可扩展答案是使用 np.diff 。在这种情况下,您应该不惜一切代价避免 for 循环。
import numpy as np
a = [1,1,1,1,4,4,4,6,6,6,6,6,1,1,1]
a = np.array(a)
# this is unequal 0 if there is a step
d = np.diff(a)
# boolean array where the steps are
is_step = d != 0
# get the indices of the steps (first one is trivial).
ics = np.where(is_step)
# get the first dimension and shift by one as you want
# the index of the element right of the step
ics_shift = ics[0] + 1
# and if you need a list
ics_list = ics_shift.tolist()
print(ics_list)
关于python - 如何在Python中查找向量(一维数组、列表)中的步骤?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62321645/