[英]Python get Index of max Value in a List: Error Value is in List but doesn't find it
我正在嘗試獲取列表中最大值的索引。 到目前為止它確實有效,但現在我需要循環進行並將這些索引和值保存在列表中。 不知何故,我收到一條錯誤消息,說我的最大值不在列表中,盡管我可以清楚地看到它在列表中。
到目前為止我的代碼做了什么:我正在遍歷 JSON 文件。 在那里我有一個包含許多值y00B
的列表。 在此列表中,我在res = file['labelindices']
之前的代碼中保存了一些索引。 現在在每個索引之間的范圍內,我想獲得最大值及其索引
這是我的代碼:
for file in json_data[sizes[i]]:
count += 1 # counting the files i am iterating trough
res = file['labelindices'] # indices i want to get the values from
y00B = file['triggerdata'] # list of my data
for r in range(0, 2):
valuesPeak = y00B[res[r]:res[r+2]] # this is right, do not ask :)
print('valuesPeak:',valuesPeak)
print('max value of current list', max(valuesPeak), 'count file = '
, count, ', length', len(valuesPeak))
if len(valuesPeak) == 0:
valuesPeak = 0
if valuesPeak == 0:
max_val.append(0)
max_index.append(0)
else:
max_val.append(max(valuesPeak))
print(y00B.index(max_val))
max_index.append(y00B.index(max_val))
這是錯誤消息和我的打印輸出:
>> ValueError: [44431] is not in list
valuesPeak: [26793, 29441, 32237, 35061, 37752, 40162, 42121, 43505, 44278, 44431, 43984, 42923, 41367, 39408, 37258, 34943, 32617, 30330]
max value of current list 44431 count file = 1 , length 18
有人可以告訴我我做錯了什么嗎? 該值在列表中很清楚。 為什么找不到? 當我在沒有for r range (0,2)
循環的情況下重寫代碼時,它工作得很好,但我需要寫 2 次,這是我試圖避免的。
我刪除了 max_val 變量 bc 似乎我只需要索引。 代碼是:
max_index = []
for i in range(0, sizesCount):
for file in json_data[sizes[i]]:
res = file['labelindices']
y00B = file['triggerdata']
for r in range(0, 2):
valuesPeak = y00B[res[r]:res[r+2]] #0 ans 2, 1 and 3
if len(valuesPeak) == 0:
valuesPeak = 0
max_index.append(0)
else:
max_index.append(y00B.index(max(valuesPeak)))
particlesize[sizes[i]].append({
'maxvalpeak685index': max_index[0],
'maxvalpeak450index': max_index[1]
})
您只需在列表中找到任何值的索引:
Mylist = [8.,9,1.2,6.,25,12,3,7.5]
Mylist.index( max(Mylist) )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.