python - 如何在Python中查找向量(一维数组、列表)中的步骤?

标签 python list vector

我想使用 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/

相关文章:

python - seaborn FacetGrid ,按行和列分隔的排名条形图

python - 如何将列表列表转换为每个列表换行且没有逗号的字符串

python - python中的多行列表理解

c - 在函数中修改 vector

python - 在 Python 2.5 中的嵌套 For Range 循环中传递参数

python - 将日转换为日期

python - numpy.where 在 pandas 数据帧中表现缓慢(2.5 小时)

python - 使用 Python 将元组列表转换为嵌套列表

c++ - 在 C++11 中创建指针 vector 的惯用方法?

c++ - 将二维 vector 写入文件? C++