我正在尝试用Python创建自己的哈希表类。我有一个用于HashEntry的类(充当私有内部类)和一个用于HashTable本身的类。我正在为此使用numpy对象数组
当我尝试实现我的“remove”方法时,我需要能够通过它的键在hashArray中找到hashEntry。这意味着我必须遍历hashArray中的hashEntry对象,并访问“entry”的每个“key”属性。当我运行代码时,我得到一个错误:
AttributeError: 'numpy.ndarray' object has no attribute 'key'
如何遍历numpy对象数组并访问它们的每个属性?还是我安排错了什么? 我的代码如下:
import numpy as np
class HashEntry():
def __init__(self, inKey="", inValue=None): #sets default values if not specified
self.key = inKey
self.value = inValue
self.state = 1 # 0 = never used, 1 = used, -1 = formerly used
def __repr__(self):
return (self.key + " -> " + str(self.value))
class DSAHashTable():
def __init__(self, tableSize):
self.count = 0
self.actualSize = self.findNextPrime(tableSize) # Set table size
self.hashArray = np.empty([self.actualSize, 1], dtype=object) #Initialize hashArray
def put(self, inKey, inValue):
newEntry = DSAHashEntry(inKey, inValue)
idx = self.hashFunction(inKey)
self.hashArray[idx] = newEntry
self.count += 1
def remove(self, inKey):
for entry in self.hashArray:
if entry.key == inKey:
np.delete(self.hashArray, inKey)
self.count -= 1
table = DSAHashTable(150)
table.put("a", "sock")
table.put("b", "shoes")
table.remove("a")
对于上下文,“findNextPrime”只是获取给定素数之后的下一个素数的类函数。(不相关)
当你做一个像
然后用
看看
entry
是什么。不要假设-验证我不认为使用对象数组而不是列表有任何优势。除了一些索引任务外,使用对象数组的速度较慢。我(和其他人)已经讨论过很多次了(尽管我不确定有没有一种简单的方法可以找到这样的答案)
编辑:我发现了这个问题。我的对象数组未满,因此有空元素。这意味着我的迭代器可以工作,但由于它通过null元素,因此会产生错误
为了解决这个问题,我在for循环下面加了一个if
希望这对将来的任何人都有帮助
相关问题 更多 >
编程相关推荐