列表列表= TypeError:不可哈希类型:'list'

时间:2019-12-03 14:39:23

标签: python python-3.x typeerror

我有这样的代码:

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:无法散列的类型:'list'。我正在尝试从列表中删除重复项,并使我的check_lst没有重复项。 我想念什么?

1 个答案:

答案 0 :(得分:1)

问题在于列表不能是集合中的键-因为它们是可变的。您可以通过将每个列表转换为元组并将元组用作集合的键来解决此问题。您发布的其余代码可与以下解决方案一起正常使用。

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))
相关问题