TypeError: unhashable type: 'list' when using built-in set function
问题描述
我有一个包含多个列表作为其元素的列表
I have a list containing multiple lists as its elements
eg: [[1,2,3,4],[4,5,6,7]]
如果我使用内置的 set 函数从这个列表中删除重复项,我会收到错误
If I use the built in set function to remove duplicates from this list, I get the error
TypeError: unhashable type: 'list'
我使用的代码是
TopP = sorted(set(TopP),reverse=True)
TopP 是一个列表,就像在例如以上
Where TopP is a list just like in the e.g. Above
set() 的这种用法是错误的吗?还有其他方法可以对上述列表进行排序吗?
Is this usage of set() wrong? Is there any other way in which I can sort the above list?
解决方案
Set 要求它们的项目是 hashable.在 Python 预定义的类型中,只有不可变的类型(例如字符串、数字和元组)是可散列的.可变类型(例如列表和字典)不可散列,因为更改其内容会更改散列并破坏查找代码.
Sets require their items to be hashable. Out of types predefined by Python only the immutable ones, such as strings, numbers, and tuples, are hashable. Mutable types, such as lists and dicts, are not hashable because a change of their contents would change the hash and break the lookup code.
因为您无论如何都要对列表进行排序,所以只需将重复删除放置在列表已排序的之后.这很容易实现,不会增加操作的算法复杂度,并且不需要将子列表更改为元组:
Since you're sorting the list anyway, just place the duplicate removal after the list is already sorted. This is easy to implement, doesn't increase algorithmic complexity of the operation, and doesn't require changing sublists to tuples:
def uniq(lst):
last = object()
for item in lst:
if item == last:
continue
yield item
last = item
def sort_and_deduplicate(l):
return list(uniq(sorted(l, reverse=True)))
相关文章