我正在研究一個練習 Python 問題。我想弄清楚如何列印關于哪個賬戶余額最高的宣告。我確信這比我想象的要容易得多,但我對編程還不夠陌生,以至于我無法弄清楚谷歌要得到我想要的答案。如果有人有時間幫助我,我將不勝感激。
account_number=["Account #1", "Account #2", "Account #3"]
total= [90, 15, 45]
到目前為止,我想出的是使用該zip函式將串列放在一起。
account_totals=list(zip(account_number, total))
highest_account=max(account_totals)[1]
print(highest_account)
這給了我最高帳戶的編號(因此列印 90),但我真正想做的是讓它列印帳戶 1。我想讓程式作業,這樣如果我可以輸入值并且串列突然改變了
account_number=["Account #1", "Account #2", "Account #3"]
total= [90, 15, 145]
然后它將列印“帳戶 3”。
我希望這是有道理的!如果有人有時間為我指明正確的方向,我將不勝感激。
uj5u.com熱心網友回復:
您可以傳入一個key引數max(),告訴函式選擇余額最高的元素(在這種情況下,余額位于元組的第二個元素中,因此我們根據每個元組的索引 1 處的元素進行比較) :
highest_account = max(account_totals, key=lambda x:x[1])
print(highest_account)
這列印:
('Account #1', 90)
uj5u.com熱心網友回復:
max為函式使用自定義鍵
account_totals = list(zip(account_number, total))
highest_account_name, highest_account_val = max(account_totals, key=lambda x: x[1])
print(highest_account_name) # Account #2
或者先用數值壓縮,max函式將按元組的第一個元素排序,這樣你就完成了
account_totals = list(zip(total, account_number))
highest_account_val, highest_account_name = max(account_totals)
print(highest_account_name) # Account #2
uj5u.com熱心網友回復:
因為這兩個串列是通過索引鏈接的(按照專案的順序),所以可以抓取最高值的索引并回傳帳號。在此作業之前,您必須將account_number串列中的專案分開,使它們成為單獨的元素。您目前在所述串列中只有一項,但您想將它們分開,如下所示,以便它們作為單獨的專案存在。
account_number=["Account #1", "Account #2", "Account #3"]
total= [90, 15, 45]
# Get the highets value
highest_value = max(total)
# Determine the index
index = total.index(highest_value)
# Cross-reference with the accounts list
account = account_number[index]
或者用一行:
account = account_number[total.index(max(total))]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/444417.html
標籤:Python
