python - 列表列表 = TypeError:不可散列的类型:'list'
问题描述
我有一个这样的代码:
lst = [['Descendant Without A Conscience', 'good', 'happy'], ['Wolf Of The Solstice', '30000', 'sad'], ['Women Of Hope', '-4000', 'neutral'], ['Pirates Of Perfection', '65467', 'neutral'], ['Warriors And Soldiers', '-5435', 'sad'], ['Butchers And Soldiers', '76542', 'sad'], ['World Of The Mountain', '6536543', 'sad'], ['Ruination Of Dusk', '-2000', 'happy'], ['Destroying The Stars', '5435', 'happy'], ['Blinded In My Enemies', '765745.5', 'happy'], ['Descendant Without A Conscience', 'good', 'happy']]
check_lst = list(set(lst))
for movie in lst:
if len(movie) > 3:
raise ValueError('Invalid input.')
elif movie[2] != movie[2].lower():
raise ValueError('Invalid input.')
elif len(lst) != len(check_lst):
raise ValueError('Invalid input.')
出于某种原因,我的 check_lst 无法正常工作,并且出现 TypeError: unhashable type: 'list'。我正在尝试从我的列表中删除重复项并使我的 check_lst 没有重复项。我错过了什么?
解决方案
问题是列表不能是集合中的键——因为它们是可变的。您可以通过将每个列表转换为元组并使用元组作为集合的键来解决此问题。您发布的其余代码将在以下解决方案中按预期工作。
lst = [['Descendant Without A Conscience', 'good', 'happy'], ['Wolf Of The Solstice', '30000', 'sad'], ['Women Of Hope', '-4000', 'neutral'], ['Pirates Of Perfection', '65467', 'neutral'], ['Warriors And Soldiers', '-5435', 'sad'], ['Butchers And Soldiers', '76542', 'sad'], ['World Of The Mountain', '6536543', 'sad'], ['Ruination Of Dusk', '-2000', 'happy'], ['Destroying The Stars', '5435', 'happy'], ['Blinded In My Enemies', '765745.5', 'happy'], ['Descendant Without A Conscience', 'good', 'happy']]
check_lst = list(set(tuple(x) for x in lst))
推荐阅读
- r - 在 R 中使用数据时间 x 轴制作图表时出现问题
- c# - 使用表达式与新关键字
- bash - 用于循环运行 java cmd 并与输入参数并行启动的 shell 脚本
- node.js - `npm install` 在 node:10.21.0-jessie-slim Dockerimage 上使用 package-lock.json 失败
- time-complexity - 算法复杂度 - 大 O 表示法
- jquery - 如何使用 html div 在 jquery 中对 json 结果进行分页?
- amazon-redshift - 来自空 S3 分区的 Redshift COPY
- arrays - 复选框数组恢复旧值已选中
- html - 增加浏览器的默认字体大小是如何工作的?
- android - 使用 Rx java 时 api 请求重复