首页 > 解决方案 > TypeError:列表索引必须是整数或切片,而不是 NoneType

问题描述

我有一些麻烦Type Error (TypeError: list indices must be integers or slices, not NoneType)

我只想在 python 中用线性探测做一个小哈希表。因此,到目前为止,我曾经制作过 insert 方法、find 方法和 hash 方法。我的插入方法有问题。这是我的代码

    def insert(self, key):

        index = self.hash(key)
        count = 0
        if self.table[index] == None or self.table[index].getValue() == "DELETED":
            self.table[index] = key
            return count + 1
        else:
            inserted = False
            while inserted != True:
                index += 1
                count += 1
                if index == self.size:
                    index = 0
                if self.table[index] == None or self.table[index].getValue() == "DELETED":
                    self.table[index] = key
                    return count

问题是这两行

if self.table[index] == None or self.table[index].getValue() == "DELETED":

我应该怎么办?我需要将我的表索引与无进行比较。有人有想法吗?

标签: pythonhashtabletypeerrornonetype

解决方案


看起来您的 self.hash 函数正在返回 None。由于 index 的值为 None 它无法在列表 self.table 中找到该值。你也可以写散列函数吗?


推荐阅读