TypeError:不可分类型:使用内置集合函数时的'list' [英] 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?
推荐答案
集合要求他们的项目是哈希。由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)))
这篇关于TypeError:不可分类型:使用内置集合函数时的'list'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!