为什么不使用ID的Python哈希列表? [英] Why doesn't Python hash lists using ID?

查看:111
本文介绍了为什么不使用ID的Python哈希列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中使用字典时,以下是不可能的:

When using a dictionary in Python, the following is impossible:

d = {}
d[[1,2,3]] = 4

因为'list'是一个不可移植的输入。但是,Python中的 id 函数返回一个保证对象生命周期唯一的对象的整数。

since 'list' is an unhashable type. However, the id function in Python returns an integer for an object that is guaranteed to be unique for the object's lifetime.

为什么Python不使用 id 来排列字典?有没有缺点?

Why doesn't Python use id to hash a dictionary? Are there drawbacks?

推荐答案

原因在这里(为什么字典键不可变

已经提出的一些不可接受的解决方案:

Some unacceptable solutions that have been proposed:


  • 按其地址(对象ID )。这不起作用,因为如果你构造一个没有找到相同值的新列表;例如:

  • Hash lists by their address (object ID). This doesn’t work because if you construct a new list with the same value it won’t be found; e.g.:

mydict = {[1,2]:'12'}

print mydict [[1,2]]

将引发 KeyError 异常,因为 [1,2] 的I​​D用于第二行与第一行不同。换句话说,字典键应该使用 == 进行比较,而不是使用

would raise a KeyError exception because the id of the [1, 2] used in the second line differs from that in the first line. In other words, dictionary keys should be compared using ==, not using is.

这篇关于为什么不使用ID的Python哈希列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆