Python索引为None,用于哈希算法
作为练习,我将一些散列算法的伪代码转换成python,除了一个问题外,它工作得很好:当我搜索一个不存在的条目时,我得到Python索引为None,用于哈希算法,python,hash,nonetype,Python,Hash,Nonetype,作为练习,我将一些散列算法的伪代码转换成python,除了一个问题外,它工作得很好:当我搜索一个不存在的条目时,我得到TypeError:“NoneType”对象是不可订阅的 我完全理解我为什么会犯这个错误,但我找不到避免它的好方法。有人能告诉我如何修改代码,使其在这种情况下不会产生错误吗 我可以使用try/except块,但这似乎有点混乱。我正在寻找最简单/最干净的方法 我的代码如下。产生错误的行是,而哈希表[index][0]!=搜索键和哈希表[索引]不是无: TABLE_SIZE = 10
TypeError:“NoneType”对象是不可订阅的
我完全理解我为什么会犯这个错误,但我找不到避免它的好方法。有人能告诉我如何修改代码,使其在这种情况下不会产生错误吗
我可以使用try/except块,但这似乎有点混乱。我正在寻找最简单/最干净的方法
我的代码如下。产生错误的行是,而哈希表[index][0]!=搜索键和哈希表[索引]不是无:
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))
只要将和
操作符周围的表达式反转即可-在Python中,和
在表达式为False
时立即短路,因此您应该始终首先检查无
。此外,None
检查可以简化一点(None
是错误的,不需要显式检查不是None
):
只要将和
操作符周围的表达式反转即可-在Python中,和
在表达式为False
时立即短路,因此您应该始终首先检查无
。此外,None
检查可以简化一点(None
是错误的,不需要显式检查不是None
):
只需切换该行,首先测试它是否为none,然后我猜它应该可以工作:而hash_table[index]不是none,hash_table[index][0]!=search_key:只需切换行,首先测试它是否为none,然后它就可以工作了,我猜:虽然hash_table[index]不是none,hash_table[index][0]!=搜索关键字:
while hash_table[index] and hash_table[index][0] != search_key: