我有一个数字数组:
y = np.random.rand(1000)我想要做的是找到y的最大值,然后从该值的位置开始,在最大值出现之前和之后,取每个第n个元素。
我似乎不能在数组中倒退。
我可以很容易地找到最大值,并从那里取每个第n个元素:
idx = np.argmax(y)
newy = y[idx::reprate] # reprate is the number of points I want to skip然而,这排除了idx之前的所有第n个点,我仍然希望获得这些点。
有没有我看不到的直截了当的方法?
发布于 2019-06-27 21:25:28
查找您想要保留的数组的第一个索引是简单的数学运算:idx % reprate
newy = y[idx%reprate::reprate]发布于 2019-06-27 21:26:38
下面是一个不带NumPy的选项:
import random
# Generating the random list
y = random.sample(range(1, 1000), 1000)
n = 3
# This will get the index of the max element
index = max(enumerate(y), key=lambda x: x[1])[0]
# This will get every `n` element
every_n_element = [y[(i + index) % len(y)] for i in range(0, len(y), n)]
print(every_n_element)发布于 2019-06-27 21:22:55
只要在你的步幅上加上一个负数,你的步幅就会倒退。
这里有一个简单的例子。这将从您提供的索引开始,然后前进2步遍历可迭代对象,然后向后遍历可迭代对象。
>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> a[4::2]
[5, 7, 9]
>>> a[4::-2]
[5, 3, 1]https://stackoverflow.com/questions/56791950
复制相似问题