【问题标题】:Getting next index after allocate max value index using Python使用Python分配最大值索引后获取下一个索引
【发布时间】:2022-06-14 00:25:13
【问题描述】:

我有以下由 10 个值组成的数组:

values = [5,4,15,2,7,1,0,25,9,6]

我想找到最大值作为索引并从中减去下一个索引,所以输出应该是两个索引之间的范围,我尝试执行以下代码:

start= 0
step=2
length=10

while start <= length:
   max_val = np.max(values)
   idx = np.where(values == max_val)
   print('max', max_val)
   print('max index', np.where(values == max_val))
   idx_all= values[i]
   
   print(max_val)
   range1= values[idx[0]] - values[idx[0]+1];
   print('range', range1)

   start=start+step

最大值及其索引是正确的,但是在查找两个索引之间的差异时出现以下输出错误:

max 25
max index (array([7], dtype=int64),)
25

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-49-de731383e093> in <module>
     15 
     16     print(max_val)
---> 17     range1= values[idx[0]] - values[idx[0]+1];
     18     print('range', range1)
     19 

TypeError: only integer scalar arrays can be converted to a scalar index

我想知道如何编辑它以使输出知道下一个索引并减去它? 谢谢。

【问题讨论】:

  • 在while循环之前values = np.array(values)
  • index, value = max(enumerate(values), key=itemgetter(1))

标签: python arrays list numpy max


猜你喜欢
  • 1970-01-01
  • 2016-07-14
  • 1970-01-01
  • 2014-05-09
  • 1970-01-01
  • 2022-01-05
  • 2021-08-13
  • 2021-12-03
  • 1970-01-01
相关资源
最近更新 更多