我正在嘗試按二維串列中的第二個元素排序,其中所有元素都是字串。我目前的排序方法的問題之一似乎是它無法對字串元素進行排序。我將如何將其更改為整數?如果可能,我還希望列印出與最高的第二個元素相關的第一個元素。在本例中為“2001”。
sqrm_price= [['1999', '7951'], ['2000', '8868'], ['2001', '12502']]
def highPrice(sqrm_price):
sort_price = sorted(sqrm_price, key = lambda x: x[1], reverse=True)
print("The year " sqrm_price[-1] " has the highest price with " sort_price[0] "$")
highPrice(sqrm_price)
我的首選輸出是“ 2001 年價格最高,為 12502$”
任何幫助將不勝感激!
uj5u.com熱心網友回復:
您可以使用 將字串轉換為 lambda 中的整數int()。另外,為什么sort什么時候可以max?
def highest_price(data):
year, price = max(data, key=lambda item: int(item[1]))
print(f"The year {year} has the highest price with ${price}")
# The year 2001 has the highest price with $12502
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/314600.html
