【问题标题】:Why do I get an unhashable type 'list' error when converting a list to a set and back为什么在将列表转换为集合并返回时出现不可散列类型“列表”错误
【发布时间】:2016-01-05 02:42:51
【问题描述】:

像这里的许多其他问题一样,我正在尝试从列表中删除重复项。但是,当我执行其他答案声称有效的代码时,我收到以下错误:

TypeError: unhashable type: 'list'

在以下代码行:

total_unique_words = list(set(total_words))

有人知道这个问题的可能解决方案吗?这是因为在大多数情况下,原始结构不是列表吗?

谢谢!

【问题讨论】:

  • 显示您用于创建 total_words 的实际代码。我怀疑你认为这应该是一个字符串列表,而实际上它可能是一个列表列表。

标签: python list set duplicates typeerror


【解决方案1】:

total_words 必须包含子列表才能发生此错误。

考虑:

>>> total_words = ['red', 'red', 'blue']
>>> list(set(total_words))
['blue', 'red']
>>> total_words = ['red', ['red', 'blue']] # contains a sublist
>>> list(set(total_words))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

【讨论】:

  • 很可能[['red', 'red', 'blue']] - 整个列表是一个子列表。
  • @MarkRansom:这是一个公平的可能性。我会把它留给你的评论来澄清。
  • 是的,就是这样,现在看起来很明显。谢谢!
猜你喜欢
  • 1970-01-01
  • 2018-02-19
  • 1970-01-01
  • 1970-01-01
  • 2017-03-11
  • 1970-01-01
  • 1970-01-01
  • 2011-09-12
  • 1970-01-01
相关资源
最近更新 更多