遍历对象数组-Python哈希表

问题描述

我正在尝试使用Python创建自己的哈希表类。我有一个用于HashEntry的类(用作私有内部类)和一个用于HashTable本身的类。我为此使用了numpy对象数组。

当我尝试实现“删除方法时,我需要能够通过其键在hashArray中找到hashEntry。这意味着我必须遍历hashArray中的hashEntry对象,并访问“ entry”的每个“ key”属性。运行代码时,出现错误

AttributeError:'numpy.ndarray'对象没有属性'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”只是用于获得给定数字后的下一个质数的类函数。 (不相关)

解决方法

当创建类似数组时

np.empty([self.actualSize,1],dtype=object)

然后用

进行迭代
for entry in self.hashArray:

看看entry是什么。不要假设-验证。

我认为使用对象数组而不是列表没有任何优势。除了一些索引任务,使用对象数组的速度较慢。我(和其他人)已经在SO上讨论了很多次(尽管我不确定是否有找到这种答案的简便方法。)

,

编辑:我发现了这个问题。我的对象数组未满,因此具有空元素。这意味着我的迭代器可以工作,但是由于它传递了null元素,因此会出现错误。

要修复,我在for循环下面放了一个 if

if entry is not None:

希望这对以后的所有人有帮助