TypeError: unhashable type: 'list' when using built-

时间:2023-01-02
本文介绍了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)))

这篇关于TypeError: unhashable type: 'list' when using built-in set function的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:Pandas/Python:如何连接两个没有重复的数据帧? 下一篇:从列表中删除重复项和原始项

相关文章

最新文章