[英]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.