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
基础教程推荐
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
