簡體   English   中英

使用Python分配最大值索引后獲取下一個索引

[英]Getting next index after allocate max value index using Python

我有以下數組,其中包含 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

我想知道如何編輯它以使輸出知道下一個索引並減去它? 謝謝你。

我認為這段代碼應該完成你正在尋找的東西:

values = [5,4,15,2,7,1,0,25,9,6]
max_val = np.max(values)
idx = list(np.where(values == max_val)[0])[0]
max_val = values[idx]
value = max_val - values[idx+1]
print(value)

對於本示例,這將輸出 16。

這輸出 16,這是真的,因為 9 在 25 旁邊

values = [5,4,15,2,7,1,0,25,9,6]
# get the maximum value first
mm = max(values)
index = 0
next_index = 0
# iterate through the array while checking for the max index
for i in range(0, len(values)):
    if(values[i]==mm):# this is the index of the maximum element
        index = i
        next_index = i+1 # break out of the loop
        break

# get the element at next index
el = values[next_index]
# get the difference with the maximum
diff = mm - el
print(diff)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM