可哈希、不可变 [英] Hashable, immutable

查看:28
本文介绍了可哈希、不可变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自最近的 SO 问题(参见 创建一个python中的字典由列表索引)我意识到我可能对python中可哈希和不可变对象的含义有一个错误的概念.

From a recent SO question (see Create a dictionary in python which is indexed by lists) I realized I probably had a wrong conception of the meaning of hashable and immutable objects in python.

  • hashable 在实践中意味着什么?
  • hashable 和 immmutable 之间的关系是什么?
  • 是否存在可散列的可变对象或不可散列的不可变对象?

推荐答案

Hashing 是过程以可重复的方式将大量数据转换为小得多的数据(通常是单个整数),以便可以在恒定时间内在表中查找(O(1)),这对于高性能算法和数据结构很重要.

Hashing is the process of converting some large amount of data into a much smaller amount (typically a single integer) in a repeatable way so that it can be looked up in a table in constant-time (O(1)), which is important for high-performance algorithms and data structures.

Immutability 是这样一种想法,即一个对象在它被改变后不会以某些重要的方式改变创建,尤其是任何可能改变该对象哈希值的方式.

Immutability is the idea that an object will not change in some important way after it has been created, especially in any way that might change the hash value of that object.

这两个想法是相关的,因为用作散列键的对象通常必须是不可变的,因此它们的散列值不会改变.如果允许更改,那么该对象在哈希表等数据结构中的位置将发生更改,然后哈希以提高效率的整个目的就会落空.

The two ideas are related because objects which are used as hash keys must typically be immutable so their hash value doesn't change. If it was allowed to change then the location of that object in a data structure such as a hashtable would change and then the whole purpose of hashing for efficiency is defeated.

要真正掌握这个想法,您应该尝试用 C/C++ 等语言实现自己的哈希表,或者阅读 HashMap 类的 Java 实现.

To really grasp the idea you should try to implement your own hashtable in a language like C/C++, or read the Java implementation of the HashMap class.

这篇关于可哈希、不可变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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