You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在字典列表中查找指定年份的最大值并返回对应国家等信息

实现方案

现有代码错误点

  • 嵌套了不必要的单字典键值对遍历逻辑,无需遍历单个国家字典的所有字段
  • max函数使用逻辑错误:你是对单个国家的字典取最大值,而非在整个数据集所有国家的目标年份数值中找最大值
  • 每次循环都会覆盖结果字典,最终只会保留最后一个国家的相关数据,无法得到最大值对应的结果

注意:你提供的样例dataset中,Albania对应的字典末尾缺少逗号,实际运行前需要补上否则会触发语法错误。

正确实现代码

简洁写法(推荐)

直接用max函数对整个数据集筛选目标年份最大值对应的条目:

def get_year_max(dataset, year):
    str_year = str(year)
    # 按目标年份的数值排序,取最大的那条国家数据
    max_record = max(dataset, key=lambda x: x[str_year])
    return {
        "country": max_record["country"],
        "year": year,
        "cases": max_record[str_year]
    }

# 调用示例,查询1991年的结果
print(get_year_max(dataset, 1991))

基础遍历写法(适合新手理解逻辑)

def get_year_max(dataset, year):
    str_year = str(year)
    max_cases = -1
    max_country = ""
    for record in dataset:
        current_cases = record[str_year]
        if current_cases > max_cases:
            max_cases = current_cases
            max_country = record["country"]
    return {
        "country": max_country,
        "year": year,
        "cases": max_cases
    }

运行结果

两种写法执行后返回的结果如下(如果多个国家同数值取第一个出现的国家):
{'country': 'Afghanistan', 'year': 1991, 'cases': 500}

内容的提问来源于stack exchange,提问作者hello_w

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 21:54:03