在学习Python艰苦之路,第39课中,您创建了一个哈希映射,可以导入并用作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))
在研究演习中,如果挑战是改变它,那么键可以有多个值。我这样做只是让它附加值,无论密钥是否存在。
def set(myMap, key, value):
bucket = get_bucket(myMap, key)
i, k, v = get_slot(myMap, key)
bucket.append((key, value))
如果我运行以下命令,它实际上会列出我输入的所有内容,而不会像第一个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'的价值观。它总是达到'Flamenco Sketches'的价值,并且不再使用'Kind of Blue'。
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”。所以我显然缺少一些东西(或几件事)。
我错过了什么?感谢。
答案 0 :(得分:0)
但是这种行为:拥有一个独特的键值对,实际上就是你想要的!如果你有两个相同的键,哈希函数不能工作,对吧!?
在您的情况下,您的行可以实现此行为:
#the key exists, replace it
bucket[i] = (key, value)
这也是Python词典的工作方式。这是一个例子:
my_dict1 = dict()
my_dict1['Miles Davis'] = 'Flamenco Sketches'
my_dict1['Miles Davis'] = 'Kind of Blue'
my_dict1['Duke Ellington'] = 'Beginning to see the light'
print(my_dict1)
{'Duke Ellington': 'Beginning to see the light', 'Miles Davis': 'Kind of Blue'}
您可以使用一种解决方法,将值设为可变对象,如果您想要多个"值,则可以附加到该值#34;与一个键相关联:
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']}