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

Python调用max函数报str与int不支持比较的TypeError问题求解

问题根因
  • 你的new_list里同时存在整型数值和字符串类型的'-1',max()函数无法直接比较整型和字符串类型的大小,因此触发类型错误。
  • 代码还存在其他隐藏问题:你定义的最大值变量是biggest_number,后续调用索引时却用了不存在的highest_number,还用到了未定义的empty_list,修复类型问题后还会报名称错误。
修复方案

你可以在读取数据时做类型转换,同时过滤无效的'-1'值,顺便同步匹配国家信息,避免后续索引匹配出错:

from typing import Dict

# 假设dataset是你已经提前定义好的全局数据集
def find_most_infected_country(year : int) -> Dict[str,any]:
    max_cases = -1
    max_country = ""
    target_year = str(year)
    
    for item in dataset:
        # 跳过Global项
        if item.get("country") == "Global":
            continue
        # 取对应年份的病例数值
        case_val = item.get(target_year, "-1")
        # 过滤无效的-1值,同时做类型转换
        if case_val == "-1":
            continue
        try:
            case_num = int(case_val)
        except ValueError:
            continue
        # 比较更新最大值和对应国家
        if case_num > max_cases:
            max_cases = case_num
            max_country = item["country"]
    
    return {
        "country": max_country,
        "year": year,
        "cases": max_cases
    }

print(find_most_infected_country(1991))
关键修改点
  • 读取病例值后统一转为整型,过滤掉字符串类型的无效值,解决类型不兼容报错
  • 省略单独存储病例列表再反向匹配索引的逻辑,避免变量名不匹配、索引错位的问题
  • 简化Global项的过滤逻辑,不用遍历整条数据的所有键,直接判断国家字段即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 00:24:03