含义
键值对存储,键用来找关联的值,这个概念被称作映射。
其中键不重复,键和值一一对应。
实现
"""
Map() 创建一个空映射,返回一个空映射集合。
put(key, val) 加入一个键值对,键存在,则替换值。
get(key) 获取对应值,不存在,则返回None。
del del map[key]删除键值对。
len() 返回映射中键值对数目。
in key in map,键存在为True,否则返回False。
优势之一: 给定一个键,可以快速找到其关联的值。
"""
class HashTable:
def __init__(self):
self.size = 11 # 尽管可任意指定,但选用一个素数很重要,可提高冲突处理算法的效率。
self.slots = [None] * self.size # 存储键
self.data = [None] * self.size # 存储值
def put(self, key, data):
hashvalue = self.hashfunction(key, len(self.slots))
if self.slots[hashvalue] == None:
self.slots[hashvalue] = key
self.data[hashvalue] = data
else:
if self.slots[hashvalue] == key:
self.data[hashvalue] = data # 替换
else:
nextslot = self.rehash(hashvalue, len(self.slots))
while self.slots[nextslot] != None and self.slots[nextslot] != key:
nextslot = self.rehash(nextslot, len(self.slots))
if self.slots[nextslot] == None:
self.slots[nextslot] = key
self.data[nextslot] = data
else:
self.data[nextslot] = data # 替换
def get(self, key):
startslot = self.hashfunction(key, len(self.slots))
data = None
stop = False
found = False
position = startslot
while self.slots[position] != None and not found and not stop:
if self.slots[position] == key:
found = True
data = self.data[position]
else:
position = self.rehash(position, len(self.slots))
if position == startslot:
stop = True
return data
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, data):
self.put(key, data)
def hashfunction(self, key, size):
return key%size
def rehash(self, oldhash, size):
return (oldhash + 1)%size
h = HashTable()
h[54] = 'cat'
h[26] = 'dog'
h[93] = 'lion'
h[17] = 'tiger'
h[77] = 'bird'
h[31] = 'cow'
h[44] = 'goat'
h[55] = 'pig'
h[20] = 'chicken'
print(h.slots)
print(h.data)