python - 不可散列的类型列表
问题描述
我们有一S
组元组。
每个元组是(string, string, list)
下面的代码:
def f(entry_set, def_dict, S):
for entry in entry_set:
if entry[1] in def_dict:
S.add((entry[0], entry[1], def_dict[entry[1]]),) // error
给出错误:TypeError: unhashable type: 'list'
def_dict
是用附加列表的值构造的。
对于添加条目,是否使用散列来查找集合元素的唯一性?
解决方案
Alist
是一个可变引用,因此不能散列,因为它引用了内存。如果您可以将列表转换为元组,则可以散列它们。
set((1, 2, [3, 4]))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-d0176c73c39f> in <module>()
----> 1 set((1, 2, [3, 4]))
TypeError: unhashable type: 'list'
相对于:
set((1, 2, (3, 4)))
{(3, 4), 1, 2}
推荐阅读
- java - 构建过程中发生错误。在项目“MyFirstProject”上运行构建器“Java Builder”时出错。java.lang.NullPointerException
- java - 为什么使用 logback 的日志包含空字符(空洞)
- javascript - 我正在尝试将检索到的标签与选定或创建的标签进行比较,如果标签不存在 perfom post request
- image - 在 Kinect 图像上变换坐标
- cypress - 从命令行运行时,如何告诉赛普拉斯隐藏 Chrome?
- java - OSGi `uses` 违反约束,即使存在兼容的导出器
- excel - VBA Excel 中的动态文件夹创建
- java - 如何测量经过的时间,不受系统时间服务器自动更新的影响
- c - 将 strcpy 应用于指向数组的指针 + some_offset
- javascript - jQuery `.find()` 找不到“匹配此选择器”的元素