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

Python字典练习题报错:unhashable type: 'list' 求解

解决Python代码报错:unhashable type: 'list' 并完成题目要求

原代码问题分析

  1. 报错根源:你写的{stone_gohan}是试图把列表直接转为集合,但列表属于不可哈希类型,因此触发unhashable type: 'list'错误。更关键的是,这完全违反了题目要求使用字典的规定。
  2. 逻辑漏洞:就算不报错,用集合对比也无法满足题目需求——题目要求每种距离的出现次数完全一致,但集合只能判断元素是否存在,无法统计次数。比如[1,1,2]和[1,2,2]的集合完全相同,但实际次数不符,不符合题目要求。

修正后的代码

n = int(input())

# 读取输入并转为整数列表,避免字符串与整数的类型判断问题
stone_gohan = list(map(int, input().split()))
stone_picolo = list(map(int, input().split()))

# 统计距离出现次数,返回字典(符合禁止使用count函数的要求)
def count_distances(lst):
    count_dict = {}
    for num in lst:
        if num in count_dict:
            count_dict[num] += 1
        else:
            count_dict[num] = 1
    return count_dict

# 生成两人的距离统计字典
dict_gohan = count_distances(stone_gohan)
dict_picolo = count_distances(stone_picolo)

# 对比字典,输出对应结果
if dict_gohan == dict_picolo:
    print("Dale Gohan!")
else:
    print("Oh, not now, Gohan! Let's try again next week.")

代码说明

  • 类型转换:把输入的字符串转为整数列表,避免因类型不一致导致的统计错误。
  • 字典统计:通过遍历列表手动计数,完全符合题目禁止使用count函数的要求。
  • 字典对比:两个字典的键值对完全一致时,说明每种距离的出现次数相同,直接满足题目判断条件。

内容的提问来源于stack exchange,提问作者um guri da programaçãO

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 02:25:40