Python 索引到 None 用于哈希算法

Python index into None for Hashing Algorithm

我已经将哈希算法的一些伪代码转换为 python 作为练习,它工作正常,除了一个问题:当我搜索一个不存在的条目时,我得到 TypeError: 'NoneType' object is not subscriptable.

我完全理解为什么会出现此错误,但我找不到避免它的好方法。有人可以告诉我如何修改代码以使其在这种情况下不会产生错误吗?

我可以使用 try/except 块,但这看起来有点乱。我正在寻找 simplest/cleanest 方法。

我的代码如下。产生错误的行是 while hash_table[index][0] != search_key and hash_table[index] is not None:

TABLE_SIZE = 10

customer_records = [  
    [45876, "Tom's data"],
    [32390, "Yolly's data"],
    [95312, "George's data"],
    [64636, "Bob's data"],
    [23467, "Susan's data"]]


def hash(key): # Anti-pattern to overwrite built in function
    return key % TABLE_SIZE


def insert(new_record, hash_table):
    index = hash(new_record[0])
    while hash_table[index] is not None:
        index += 1
        if index > TABLE_SIZE:
            index = 0
    hash_table[index] = new_record


def find_record(search_key, hash_table):
    index = hash(search_key)
    while hash_table[index][0] != search_key and hash_table[index] is not None:
        index += 1
        if index > TABLE_SIZE:
            index = 0
    if hash_table[index] is not None:
        return hash_table[index]


my_hash_table = [None] * TABLE_SIZE   

for record in customer_records:
    insert(record, my_hash_table)

print(find_record(45873, my_hash_table)) 

只需反转 and 运算符周围的表达式 - 在 Python 中,一旦表达式为 Falseand 就会短路,因此您应该始终检查对于 None 第一个 。此外,None 检查可以稍微简化(None 是假的,没有必要显式检查 is not None):

while hash_table[index] and hash_table[index][0] != search_key: