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

时间:2017-11-23 09:00:56

标签: python

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

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)

max应该选择最高值吗?如果我没有弄错,并且枚举应该选择值及其索引,当我将它们打印在一起时,我应该得到最高值,并且它位于列表中。至少这就是我想要做的事情。被选为最高分的索引应该与获得该分数的玩家以及他们如何被列出的分享相同的索引。

任何帮助都会很棒 感谢

更新

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!')

2 个答案:

答案 0 :(得分:2)

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

winner = max(score)

如果您还想要索引,可以按照@ChrisRand在评论中的建议进行操作:

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

答案 1 :(得分:0)

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

>>> 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)即可。