PYthon在hashmap中构建第三层列表

2024-09-30 20:22:30 发布

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

我目前在Ex39学习Python的艰难方式:http://learnpythonthehardway.org/book/ex39.html

我现在真的被这段代码卡住了,我试图在代码中添加一个“第三层”bucket,这样每个键都有自己的字典,这样键就可以保存多个值。在

代码太多,所以我无法将其全部粘贴在这里,但是如果您单击链接并向下滚动,您将看到一个副标题:“三级列表”,该副标题下的最后一句/第三段如下:

如果要进一步研究此代码,请将其更改为支持每个键的多个值

我已经试了两天了,现在我开始明白了。我就是想不出办法。在

如果有人能给我一些指导,我将不胜感激。在

在实现代码后,我收到以下错误:

File "ex39_test.py", line 34, in <module>
print "Michigan has: %s" % hashmap2.get(cities, hashmap2.get(states,     'Michigan'))
File "C:\python27\hashmap2.py", line 27, in get
i, k, vlist = get_slot(aMap, key, default=default)
File "C:\python27\hashmap2.py", line 18, in get_slot
bucket = get_bucket(aMap, key)
File "C:\python27\hashmap2.py", line 13, in get_bucket
bucket_id = hash_key(aMap, key)
File "C:\python27\hashmap2.py", line 10, in hash_key

在执行代码建议的这一部分之后:

^{pr2}$

我把'key'变量变成了一个可变项-它现在作为一个值以及它自己列表的键在一个列表中。在

所以现在我不能在之前的散列函数中散列它


Tags: key代码inpy列表getbucketline
2条回答

我相信,通过添加第三级,他们说的是,与其为每个键都有一个值,不如有一个列表。在

所以我们换套:

def set(aMap, key, value):
"""Sets the key to the value, only adds new values"""
  bucket = get_bucket(aMap, key)
  i, k, vlist = get_slot(aMap, key)
  if i >= 0:
      # check if value is already in list, if so, do nothing
      if value in vlist:
            return
      # the key exists, so just add they value to it
      vlist.append(value)
  else:
      # the key is not in table, add a list for the key
      # allows multiple values for each key
      bucket.append((key, list(value)))

我相信其他函数没有改变。注意get()将返回一个列表,而不是一个值。在

我也尝试在哈希图中建立第三层,我做了,这就是我的代码实现的。在

Because type 'list' is not hashable,so let's keep the 'key' type still 'string',and made 'value' type list. 附言:我是一名来自中国的学生,请原谅我奇怪的英语表达。只是想帮忙!在

这是我代码的关键部分:

def set(aMap, key, value):
'''Sets the key to the value, replacing an existing value.'''
    bucket = get_bucket(aMap, key)
    i, k, vlist = get_slot(aMap, key)

    if i >= 0:
    # the key exists, append it
        vlist.append(value)
    else:
    # the key does not, append to creat it
        bucket.append((key,[value])) 
    # attention! the key is string and value becomes list,which is the 3rd layer of bucket.

其他功能也需要相应的改变。在

注意ex39中的这个语句_测试.py公司名称:

^{pr2}$

在上面的语句中,当我们调用hashmap.get函数时,它将返回一个值,但该值的类型应为list,并且它将成为hashmap.get当我们再次调用它的时候函数! 如果你没有注意到它,计算机会把这个键散列进去,它的类型是list,这将导致一个不可修复的错误。在

这就是我在hashmap.py公司名称:

^{3}$

相关问题 更多 >