在Python中,哈希表可以通过内置的字典(dictionary)类型来实现。字典是Python中的一种数据结构,它允许我们存储键值对,每个键映射到一个值。字典的键必须是可哈希的,这意味着它们需要实现`__hash__()`方法,并且如果两个对象相等,它们必须具有相同的哈希值。
创建一个空字典
hash_table = {}
插入键值对
hash_table['apple'] = 'A fruit'
hash_table = 'The answer to life, the universe, and everything'
查找键对应的值
print(hash_table['apple']) 输出:A fruit
print(hash_table) 输出:The answer to life, the universe, and everything
检查键是否在字典中
print('apple' in hash_table) 输出:True
print(42 in hash_table) 输出:True
删除键值对
del hash_table['apple']
尝试查找已删除的键
print(hash_table['apple']) 输出:None
如果你需要更高级的哈希表功能,比如自定义哈希函数或解决哈希冲突,你可以创建自定义的哈希表类。以下是一个简单的自定义哈希表类的示例,它使用链地址法来解决冲突:
class HashTable:
def __init__(self, size=10):
self.size = size
self.table = [[] for _ in range(self.size)]
def _hash_function(self, key):
return sum(ord(c) for c in key) % self.size
def insert(self, key, value):
index = self._hash_function(key)
for item in self.table[index]:
if item == key:
item = value 更新已有的键
return
self.table[index].append([key, value]) 插入新的键值对
def search(self, key):
index = self._hash_function(key)
for item in self.table[index]:
if item == key:
return item 返回键对应的值
return None 如果键不存在,返回None
def delete(self, key):
index = self._hash_function(key)
for i, item in enumerate(self.table[index]):
if item == key:
del self.table[index][i] 删除键值对
return
使用自定义哈希表类的示例:
创建一个大小为10的哈希表
hash_table = HashTable(10)
插入键值对
hash_table.insert('apple', 'A fruit')
hash_table.insert(42, 'The answer to life, the universe, and everything')
查找键对应的值
print(hash_table.search('apple')) 输出:A fruit
print(hash_table.search(42)) 输出:The answer to life, the universe, and everything
删除键值对
hash_table.delete('apple')
尝试查找已删除的键
print(hash_table.search('apple')) 输出:None
请注意,这个自定义哈希表类是非常基础的,实际应用中可能需要更复杂的功能和优化。