繁体   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