簡體   English   中英

使用 For 循環在列表中查找最大值

[英]Find highest value in a list with For loop

我有一個分數列表,我想找到列表中的最高值(在下面的示例中,它是值 80)。

scores = [60,29,60,43,10,9,80,45,23,80,56,4]

highest_score = 0

for i in scores:
    
    if i >= highest_score:
        highest_score = i
        print (highest_score, scores.index(highest_score) )

對於最高得分,它返回[60,60,80,80] highest_scores而我只想獲得最高值80 對於scores.index(highest_score) ,它給了我索引[0,0,6,6] ,而我想獲得最高值的索引 - 那應該是[6,6]

如何改進我的代碼以獲得預期的結果?

如果您正在尋找[60,29,60,43,10,9,80,45,23,80,56,4]中最高值的索引,我認為您的意思是您想要: [6, 9] .

假設您想要算法的“本機”實現而不必求助於max() function,並且您想要我建議您使用的索引enumerate(scores)

scores = [60,29,60,43,10,9,80,45,23,80,56,4]

highest_score = scores[0]
indexes = []

for i, s in enumerate(scores):
  if s > highest_score:
    indexes = []
  if s >= highest_score:
    indexes.append(i)
    highest_score = s

print(highest_score, indexes)

結果:

80 [6, 9]

您可以通過以下方式找到最大值:

max(scores)

返回80

您正在做的錯誤是在 print 語句的縮進中。 它應該在循環之外。 試試下面的代碼:

scores = [60, 29, 60, 43, 10, 9, 80, 45, 23, 80, 56, 4]

highest_score = 0

for i in scores:
    if i >= highest_score:
        highest_score = I

# find all indices of the highest_score
indices = [i for i, x in enumerate(scores) if x == highest_score]
print(highest_score, indices)

我還編寫了一個列表理解,用於查找列表中最高分的所有索引,因為您的代碼只會返回第一次出現的索引。

Output:

80 [6, 9]

有更好的方法可以做到這一點,但是由於您想使用 for 循環來做到這一點,這應該可以:

scores = [60,29,60,43,10,9,80,45,23,80,56,4]

highest_score = 0
index_list = []

for i in scores:   
   if i >= highest_score:
       highest_score = i

for i in scores:
   if i == highest_score:
       index_list.append(scores.index(i))

print (highest_score , index_list )

Output:

>>> 80 [6, 6]

你可以試試:

scores = [60,29,60,43,10,9,80,45,23,80,56,4]

highest_score = 0
highest_score_index=[]

for index, score in enumerate(scores):
    if score > highest_score:
        highest_score = score
        highest_score_index.clear()
        highest_score_index.append(index)
    elif score == highest_score:
        highest_score_index.append(index)
        
print (highest_score, highest_score_index )

對於單個 for 循環。

返回: 80 [6, 9]

scores = [60,29,60,43,10,9,80,45,23,80,56,4]
highest_score = None
highest_score_indexes = []

for index, value in enumerate(scores):
    if index == 0:
        highest_score = value
        highest_score_indexes.append(index)
    else:
        if highest_score > value:
            pass
        elif highest_score == value:
            highest_score_indexes.append(index)
        elif highest_score < value:
            highest_score = value
            highest_score_indexes = [index]

print("heighest score {}".format(highest_score))
print("heighest score indexes {}".format(highest_score_indexes`enter code here`))

暫無
暫無

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

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