Python处理DVD影片列表构建查询字典遇不可哈希错误求助
问题解决方案
错误原因
你遇到的unhashable type: 'list'报错,核心原因是re.findall的返回值为匹配结果组成的列表,你直接将列表作为元素存入movieTitle、movieYear,而列表属于可变类型,无法作为字典的键使用,和标题是否带空格没有关联。
优化后实现方案
推荐直接用正则一次匹配提取标题和年份,同时对标题做标准化处理,直接存入字典,逻辑更简洁,也兼容所有带空格的多词标题:
第一步:提取内容存入字典
import re movie_dict = {} # L为从txt文件读取的原始行列表 for lin in L: # 正则适配你给出的DVD条目格式,自动拆分标题和年份 match_result = re.match(r'^(.*?)\s*\((\d{4})\)$', lin.strip()) if match_result: # 提取标题并标准化,和后续输入查询的处理逻辑对齐 raw_title = match_result.group(1).strip() normalized_title = raw_title.lower().title() # 提取年份 release_year = match_result.group(2) # 存入字典,字符串类型的标题可直接作为键 movie_dict[normalized_title] = release_year
第二步:查询逻辑调整
user_input = input().strip().lower().title() if user_input in movie_dict: print(f"{user_input} ({movie_dict[user_input]}) DVD is AVAILABLE") else: print("THIS DVD IS NOT AVAILABLE")
原有代码最小修改方案
如果你不想调整现有逻辑,只需要在提取时取re.findall返回列表的第一个元素即可:
import re movie_dict = {} movieTitle = [] movieYear = [] for lin in L: # 提取匹配结果的第一个元素,转为字符串 movieName = re.findall('(^.*)\s', lin)[0].strip().lower().title() movieTitle.append(movieName) movieYr = re.findall('(\(....\))$', lin)[0] movieYear.append(movieYr) # 遍历两个列表生成字典 for title, yr in zip(movieTitle, movieYear): movie_dict[title] = yr
内容的提问来源于stack exchange,提问作者ArtimusMaximus
相关产品推荐
相关产品推荐

