学习Python定义get为hashmap中的键返回多个值

2024-09-30 10:37:21 发布

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

在第39课学习Python的Hard Way中,您将创建一个hashmap来导入并用作Python内置字典的模拟。在

最初,它是这样编写的,hashmap一次只允许一个键:

def get(aMap, key, default = None):
    """Gets the value in a bucket for the given key, or the default"""
    i, k, v = get_slot(aMap, key, default = default)
    return k, v

def set(aMap, key, value):
    """Sets the key to the value, replacing any existing values"""
    bucket = get_bucket(aMap, key)
    i, k, v = get_slot(aMap, key)

    if i >= 0:
    #the key exists, replace it
        bucket[i] = (key, value)
    else:
    #The key does not exist, append and create it
        bucket.append((key, value))

在学习练习中,如果挑战是改变它,那么键可以有多个值。我只是让它附加值,不管键是否存在。在

^{2}$

如果我运行以下命令,它实际上会列出我输入的所有内容,而不会像第一个set函数那样覆盖:

jazz = myHashmap2.new()
myHashmap2.set(jazz, 'Miles Davis', 'Flamenco Sketches')
myHashmap2.set(jazz, 'Miles Davis', 'Kind of Blue')
myHashmap2.set(jazz, 'Duke Ellington', 'Beginning to see the light')
myHashmap2.set(jazz, 'Billy Strayhorn', 'Lush Life')

print "-----List Test-----"
myHashmap2.list(jazz)

我得到:

-----List Test-----   
Billy Strayhorn Lush Life
Miles Davis Flamenco Sketches
Miles Davis Kind of Blue
Duke Ellington Beginning to see the light

但是,我似乎无法让“get”函数同时打印“Miles Davis”值。它总是达到“弗拉门戈草图”的值,而不是“蓝色”。在

print "-----Get Test-----"
print ex39_hashmap.get(jazz, 'Miles Davis')
print ex39_hashmap.get(jazz, 'Duke Ellington')
print ex39_hashmap.get(jazz, 'Billy Strayhorn')

-----Get Test-----
('Miles Davis', 'Flamenco Sketches')
('Duke Ellington', 'Beginning to see the light')
('Billy Strayhorn', 'Lush Life')

我试过几种方法:

def get(myMap, key, default = None):
    i, k, v = get_slot(myMap, key, default = default)

    if k == key:
        return (k, v)

def get(myMap, key, default = None):
    bucket = get_bucket(myMap, key)
    i, k, v = get_slot(myMap, key, default = default)
    for i, k in bucket:
        if k == key:
            return (k, v)

我想它应该是某种循环,当它第一次看到它时,它不会停止运行,但是我不知道该怎么做。在

另外,我编写的循环只对每个get返回“None”。所以我显然遗漏了一些东西。在

我错过了什么?谢谢。在


Tags: thekeydefaultgetbucketvalueprintset
1条回答
网友
1楼 · 发布于 2024-09-30 10:37:21

但是这种行为:拥有一个唯一的键值对,实际上是你想要的!如果你有两个相同的键,哈希函数就不能工作了,对吧!?。在

在这种情况下,你的行为是通过以下方式实现的:

#the key exists, replace it
bucket[i] = (key, value)

这也是Python字典的工作原理。下面是一个例子:

^{pr2}$

如果您想让多个“值”与一个键相关联,您可以有一个变通方法,使该值成为可变对象并附加到该对象:

my_dict2 = dict()
my_dict2['Miles Davis'] = ['Flamenco Sketches']
my_dict2['Miles Davis'].append('Kind of Blue')
my_dict2['Duke Ellington'] = 'Beginning to see the light'

print(my_dict2)

{'Duke Ellington': 'Beginning to see the light', 'Miles Davis': ['Flamenco Sketches', 'Kind of Blue']}

相关问题 更多 >

    热门问题