如何修复正则统计字符串数字次数时的‘不可哈希类型:列表’错误?
修复代码:统计字符串中数字出现次数的问题
你的代码报错unhashable type: list有两个核心原因,对应两处修改:
错误原因与修复点
re.findall参数类型错误:re.findall的第一个参数必须是字符串类型的正则表达式,你写的[i]是列表,不符合要求。需要把整数i转为字符串str(i),作为匹配单个数字的模式。- 字典键的类型错误:你用
number(re.findall返回的列表)作为字典的键,但列表是不可哈希的类型,不能作为字典键。应该用当前数字的字符串形式(如'0'、'2')作为键。
修复后的完整代码
import re string = "Tran Yen Nhi sn 23 06 2003" digit_count = {} for i in range(10): num_str = str(i) # 查找所有匹配当前数字的字符 matches = re.findall(num_str, string) count = len(matches) # 仅保留出现过的数字(和示例结果一致) if count > 0: digit_count[num_str] = count print(digit_count)
运行后输出:
{'0': 3, '2': 2, '3': 2, '6': 1}
可选调整
如果你需要保留0-9所有数字的统计结果(包括出现次数为0的),只需去掉if count > 0的判断:
import re string = "Tran Yen Nhi sn 23 06 2003" digit_count = {} for i in range(10): num_str = str(i) matches = re.findall(num_str, string) digit_count[num_str] = len(matches) print(digit_count)
输出会包含所有数字:
{'0': 3, '1': 0, '2': 2, '3': 2, '4': 0, '5': 0, '6': 1, '7': 0, '8': 0, '9': 0}
内容的提问来源于stack exchange,提问作者Vinh Nguyễn Thành
相关产品推荐
相关产品推荐

