首页 > 解决方案 > 对二维字符串列表python进行排序

问题描述

我正在尝试按二维列表中的第二个元素进行排序,其中所有元素都是字符串。我当前的排序方法的问题之一似乎是它无法对字符串元素进行排序。我将如何将其更改为整数?如果可能的话,我还希望将第一个元素与最高的第二个元素相关联。在这种情况下为“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 美元”

任何帮助将不胜感激!

标签: pythonsortingmultidimensional-array

解决方案


您可以使用 将字符串转换为 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

推荐阅读