附加键和值

2024-04-27 17:41:55 发布

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

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

    def __init__(self, numBuckets):
        """Creates 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)
                return
        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(29)
for i in range(20):
    key = random.randint(0, 10**5)
    D.addEntry(key, i)
print "The value of the intDict is: "
print D
print '\n', "The buckets are: "
for hashBucket in D.buckets:
    print ' ', hashBucket

有人能给我解释一下addEntry(self, dictKey, dictVal)是做什么的吗?以及如何。 在johnguttags介绍了使用Python进行计算和编程之后,我对一般编程还是比较陌生的,目前还停留在这一点上。 顺便说一句,print "The value of intDict is: ",运行时只打印29个空列表。为什么?你知道吗


Tags: inselfforreturndefrangeresultprint