附加到子列表 附加到每个子列表 [英] append to a sublist appends to every sublist

查看:31
本文介绍了附加到子列表 附加到每个子列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个包含 10 个桶列表的简单哈希表.使用内置的 hash() 计算索引,然后对表大小进行取模.但是,当我尝试将对象附加到该索引处的存储桶列表时,它会被附加到每个存储桶列表中.我尝试以不同的方式定义 add_HT,但我一直得到相同的结果.我做错了什么?

I'm writing a simple hash table with a set of 10 bucket lists. The index is calculated using the built-in hash() and then modulo the table size. However, when I try to append the object to the bucket list at that index, it gets appended to every bucket list instead. I've tried defining add_HT different ways but i keep getting the same result. What am I doing wrong?

size = 10
HT = [ [] ] * size

def add_HT(data):
    index = hash(data) % size
    HT[index].append(data)

print HT

[[], [], [], [], [], [], [], [], [], []]

add_HT('hello')

[['hello'], ['hello'], ['hello'], ['hello'], ['hello'], ['hello'], ['hello'], ['hello'], ['hello'], ['hello']]

推荐答案

HT = [ [] ] * size 使 size 个指向的指针相同列表.add_HT 不是这里的问题.您需要将 HT 定义为 [[] for i in xrange(size)].

HT = [ [] ] * size makes size number of pointers to the same list. add_HT isn't the problem here. You need to define HT as [[] for i in xrange(size)].

这篇关于附加到子列表 附加到每个子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆