1、散列的映射
Map()创建一个空映射,然后回到一个空映射集合。
在put(key,val)的映射中添加新的键值对。若键已存在,则用新值代替旧值。
get返回key对应的值。如果key不存在,返回none。
del通过del map[key]语句从映射中删除键-值对。
len()回到映射中存储的键-值对的数目。
当键存在时,in通过keyinmap等语句返回True,否则返回False。
2、实例
class Map(object): def __init__(self,size=11): self.size = size self.__slots = [None] * self.size self.__data = [None] * self.size def put(self, key, val): hashvalue = self.hashfunction(key, len(self.__slots)) if self.__slots[hashvalue] == None: self.__slots[hashvalue] = key self.__data[hashvalue] = val else: if self.__slots[hashvalue] == key: self.__data[hashvalue] = val 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] = val else: self.__data[nextslot] = val 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 delete(self,key): pass def __getitem__(self, key): return self.get(key) def __setitem__(self, key, val): self.put(key, val) def __delitem__(self, key): self.delete(key) def len(self): pass def hashfunction(self, key, size): return key % size def rehash(self, oldhash, size): return (oldhash + 1) % size
以上就是python哈希散列的映射,希望对大家有所帮助。更多Python学习指路:python基础教程