TypeError: unhashable type: #39;list#39; 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:TypeError: unhashable type: 'list' when using built-i


基础教程推荐
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 包装空间模型 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01