Python:如何创建嵌套容器的哈希

发布于 2024-10-03 09:25:14 字数 225 浏览 1 评论 0原文

[Python 3.1]

我正在尝试为可能包含深度未知的嵌套容器的容器创建哈希。在层次结构的所有级别上,都只有内置类型。有什么好的方法可以做到这一点?

为什么我需要它:

我将一些计算的结果缓存在pickle对象(在磁盘上)中。如果使用不同的参数调用该函数,我需要使该缓存文件失效(这种情况很少发生,因此我不会将多个文件保存到磁盘)。哈希值将用于比较参数。

[Python 3.1]

I am trying to create a hash for a container that may have nested containers in it, with unknown depth. At all levels of the hierarchy, there are only built-in types. What's a good way to do that?

Why I need it:

I am caching the result of some calculations in a pickle object (on disk). I would need to invalidate that cached file if the function is called with different parameters (this happens rarely, so I'm not going to save more than one file to disk). The hash will be used to compare the parameters.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

北方的巷 2024-10-10 09:25:14

如果所有容器都是元组,并且所有包含的对象都是可哈希的,那么主容器应该是可哈希的。

If all the containers are tuples, and all the contained objects are hashable, then the main container should be hashable.

余生一个溪 2024-10-10 09:25:14

您可以将参数序列化为 JSON 之类的内容,然后将其用于哈希。

You could just serialize the parameters into something like JSON, and use that for the hash.

私野 2024-10-10 09:25:14

我将使用 json 序列化作为字符串来完成此操作[如果仍然需要,则对该字符串进行哈希处理]。

from simplejson import dumps

def hash_data(data):
    return hash(dumps(data))

I would do it with json serialization as a string [and then hash that string if it's still necessary].

from simplejson import dumps

def hash_data(data):
    return hash(dumps(data))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文