繁体   English   中英

从最大值开始获取列表的第n个元素

[英]Get every n-th element of list starting from maximum value

我有一个数字数组:

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个点。

有没有我看不到的简单方法?

查找要保留的数组的第一个索引很简单: idx % reprate

newy = y[idx%reprate::reprate]

只需在步幅上添加负数,就会倒退。

这里简单的例子。 这将从您提供的索引开始,然后跨2向前遍历可迭代对象,然后向后遍历可迭代对象。

>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> a[4::2]
[5, 7, 9]
>>> a[4::-2]
[5, 3, 1]

这是没有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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM