【问题标题】:list of lists = TypeError: unhashable type: 'list'列表列表 = TypeError:不可散列的类型:'list'
【发布时间】:2020-03-28 06:45:50
【问题描述】:

我有一个这样的代码:

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 没有重复项。 我错过了什么?

【问题讨论】:

  • set(lst) 很可能是您的问题。集合的键不能是列表,由于lst是列表的列表,确实如此。
  • 引发此错误的简单方法:set([[]])

标签: python python-3.x list set typeerror


【解决方案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))

【讨论】:

  • 对于其余的代码,我们甚至不需要最终转换为列表,因为列表仅用于确定长度。我们可以通过len{tuple(entry) for entry in lst}获取长度。
  • 同意 - 我将其保留为一个列表,因为我不确定 OP 的其余代码是否需要它 - 并且保持变量命名相同,check_lst 应该是一个列表是有道理的.
猜你喜欢
  • 2015-12-01
  • 2019-01-29
  • 2018-12-26
  • 2013-10-22
  • 2013-01-23
  • 2017-06-21
  • 1970-01-01
  • 1970-01-01
  • 2018-10-05
相关资源
最近更新 更多