如何修复Python代码运行报错TypeError: unhashable type: 'list'
报错原因及修复方案
错误根因
- 变量名不匹配:函数定义的形参为
gen_to_mov、mov_to_avg,但函数内部错误使用了全局变量gtom、avg_rat,会导致变量取值异常。 - 核心
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
相关产品推荐
相关产品推荐

