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

TypeError: unhashable type: #39;list#39; when using built-in set function(TypeError: unhashable type: list when using built-in set function)
本文介绍了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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)