向哈希表添加数据时,下面的for循环有什么用?

2024-04-27 20:53:09 发布

您现在位置:Python中文网/ 问答频道 /正文

for i in range(len(hashBucket)):
        if hashBucket[i][0] == dictKey:
            hashBucket[i] = (dictKey, dictVal)

使用哈希实现字典。 以下是完整代码:

class intDict(object):
"""A dictionary with integer keys"""

def __init__(self, numBuckets):
    """Create an empty dictionary"""
    self.buckets = []
    self.numBuckets = numBuckets
    for i in range(numBuckets):
        self.buckets.append([])

这里

def addEntry(self, dictKey, dictVal):
    """Assumes dictKey an int. Adds an entry."""
    hashBucket = self.buckets[dictKey%self.numBuckets]
    for i in range(len(hashBucket)):
        if hashBucket[i][0] == dictKey:
            hashBucket[i] = (dictKey, dictVal)
    hashBucket.append((dictKey, dictVal))

def getValue(self, dictKey):
    """Assumes dictKey an int. Returns entry associated
       with the key dictKey"""
    hashBucket = self.buckets[dictKey%self.numBuckets]
    for e in hashBucket:
        if e[0] == dictKey:
            return e[1]
    return None

def __str__(self):
    result = '{'
    for b in self.buckets:
        for e in b:
            result = result + str(e[0]) + ':' + str(e[1]) + ','
    return result[:-1] + '}' 
import random

D = intDict(10)
for  i in range(20):
  key = random.choice(range(100))
  D.addEntry(key, i)     

print("the value of the intDict")
print(D)

for hashBucket in D.buckets:
    print(' ', hashBucket)

即使去掉for循环,我也得到了类似的结果。 我在《使用python的计算和编程入门》一书中看到了这段代码


Tags: theinselfanforifdefrange
1条回答
网友
1楼 · 发布于 2024-04-27 20:53:09

Hashmaps是将键值对保存在一个大列表中的一种选择。它们将列表划分为更小的列表,以便在进行查找或插入时检查是否匹配的项目更少

一旦找到了正确的hashbucket,您询问的代码将检查该BUCKET中的每个条目,以查看它们的键是否匹配,如果匹配,则返回值

双关语的意思是,关键是要有足够的buxket,它们足够小,可以快速扫描,但不要太多,以至于占用太多内存

相关问题 更多 >