python - 对二维字符串列表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 美元”
任何帮助将不胜感激!
解决方案
您可以使用 将字符串转换为 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
推荐阅读
- node.js - Windows 中的 Node.Js 线程池
- amazon-web-services - AWS 文本无效参数异常
- amazon-web-services - 如果我将 EC2 实例的角色分配给 S3,这是否意味着所有实例操作系统级别的用户都对 S3 具有相同的访问权限
- spring - 删除弹性搜索响应中 doc_count 为零的存储桶
- javascript - 如何在 phpMyAdmin 的世界地图上显示人口统计数据?
- mongodb - 在 Handlebars 304 错误中嵌套 {{#each}}
- reactjs - 当我单击仪表板中的菜单时,React 路由器显示空白页面
- java - 为什么直接同步一个 ArrayList 可以确保它对其他线程的可见性
- c# - 使用 C# 的类型(反射)是不好的做法吗?
- windows - 使用 PowerShell 创建 Windows 计划任务时停止现有实例选项