問題描述
我有一個包含多個列表作為其元素的列表
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)))
這篇關于TypeError: unhashable type: 'list' when using built-in set function的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!