繁体   English   中英

如何在列表中找到max()并使用max()查找其索引值?

[英]How to find max() in a list and find its index value as well using max()?

我只是想知道是否有人可以发现我在做什么错,我的印象是以下代码可以找到最大数量和最大数量的索引。 这是下面我使用的代码。

def select_winner():
    print('The game scores are:')
    for i in range (4):
        print(Players[i], ' = ', score[i])
    winner = max(enumerate(score))
    print('----------------')
    print()
    print('The Winner is ', Players[winner[0]], ' with ', str(winner[1]),' 
    points!')
    print(winner)

输出:

#The game scores are:
#Jarrah  =  86
#Reza  =  121
#Marge  =  72
#Homer  =  91
#----------------
#The Winner is  Homer  with  91  points!
#(3, 91)

最大应该选择最高值吧? 如果我没记错的话,枚举应该选择该值及其索引,当我将它们一起打印时,我应该得到最高的值及其在列表中的位置。 至少这就是我正在尝试做的事情。 被选为最高分的分数的索引应该与获得该分数的玩家共享相同的索引,也就是如何将其列出。

任何帮助将非常感谢

更新:

def select_winner():
    print('The game scores are:')
    for i in range (4):
        print(Players[i], ' = ', score[i])
    winner =(max(score))
    print('----------------')
    print()
    print('The Winner is '+ Players[winner[0]]+ ' with '+ str(winner[1])+ ' 
    points!')
    print(winner)

输出:

#The game scores are:
#Jarrah  =  91
#Baldwin  =  73
#Kepa  =  112
#Long  =  106
#----------------
#in select_winner
#print('The Winner is '+ Players[winner[0]]+ ' with '+ str(winner[1])+ ' 
#points!')
#TypeError: 'int' object is not subscriptable

任何人都知道解决方法,max()本身是否会拉出最大编号所在的索引? 如果没有,有办法吗?

固定!:

def select_winner():
    k=0
    print('The game scores are:')
    for i in range (4):
    print(Players[i], ' = ', score[i])
    winner2=(score.index(max(score)))
    winner=str(max(score))
    print('----------------')
    print()
    print('The Winner is '+ Players[winner2]+ ' with '+ winner + ' points!')

您想使用max(score) ; enumerate返回一个tuple (index, element) 元组的最大值在第一个元素上求值,在这种情况下,它将始终是最后一个(最大索引)。

winner = max(score)

如果还需要索引,则可以按照@ChrisRand在注释中建议的方法进行操作:

winner = max(enumerate(score), key= lambda x: x[1])

枚举为您提供索引和项目的元组。 例如,如果

>>> score
[1, 2, 4, 9, 6, 8, 3, 7, 4, 8]
>>> [i for i in enumerate(score)]
[(0, 1), (1, 2), (2, 4), (3, 9), (4, 6), (5, 8), (6, 3), (7, 7), (8, 4), (9, 8)]

只需一个简单的max(score)为您工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM