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

如何修复Python代码运行报错TypeError: unhashable type: 'list'

报错原因及修复方案

错误根因

  1. 变量名不匹配:函数定义的形参为gen_to_mov、mov_to_avg,但函数内部错误使用了全局变量gtom、avg_rat,会导致变量取值异常。
  2. 核心TypeError: unhashable type: 'list'报错触发原因:Python 字典的键必须是可哈希的不可变类型(如字符串、数字、元组),列表属于可变类型,不能作为字典键。代码中两处存在把列表作为字典键的操作:
  • avg_rat[gtom[i]]中gtom[i]的返回值为列表,作为avg_rat的键触发报错
  • 循环变量i如果是列表,作为top_n_rated_games的键也会触发报错

修复步骤

  • 统一函数内部变量名,优先使用传入的形参,避免依赖全局变量
  • 把作为字典键的列表转成可哈希的类型

修复后代码示例

def game_popularity(gen_to_mov, mov_to_avg, n = 5):
    top_n_rated_games = {}
    # 替换为传入的形参,不依赖全局变量
    for i in gen_to_mov:
        current_val = gen_to_mov[i]
        # 列表转元组后作为字典键
        key = tuple(current_val) if isinstance(current_val, list) else current_val
        if mov_to_avg[key] == n:
            # 若循环变量i是列表也做转换
            res_key = tuple(i) if isinstance(i, list) else i
            top_n_rated_games[res_key] = current_val
    return top_n_rated_games
print(game_popularity(gtom, avg_rat))

补充:如果业务场景不允许最终结果的键为元组,也可以将列表拼接为字符串作为键,例如'-'.join(map(str, current_val)),可根据实际需求调整转换规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 22:27:01