Why do I get an unhashable type 'list' error when converting a list to a set and back

天大地大妈咪最大 提交于 2019-12-04 06:05:03

问题


Like many other questions on here, I'm attempting to remove duplicates from a list. However, when I execute code that other answers claim work I get the following error:

TypeError: unhashable type: 'list'

on the following line of code:

total_unique_words = list(set(total_words))

Does anyone know a possible solution to this problem? Is this because in most cases the original structure isn't a list?

Thanks!


回答1:


total_words must contain sublists for this error to occur.

Consider:

>>> 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'


来源:https://stackoverflow.com/questions/32999483/why-do-i-get-an-unhashable-type-list-error-when-converting-a-list-to-a-set-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!