Python:如何创建嵌套容器的哈希
[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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果所有容器都是元组,并且所有包含的对象都是可哈希的,那么主容器应该是可哈希的。
If all the containers are tuples, and all the contained objects are hashable, then the main container should be hashable.
您可以将参数序列化为 JSON 之类的内容,然后将其用于哈希。
You could just serialize the parameters into something like JSON, and use that for the hash.
我将使用 json 序列化作为字符串来完成此操作[如果仍然需要,则对该字符串进行哈希处理]。
I would do it with json serialization as a string [and then hash that string if it's still necessary].