附加到子列表 附加到每个子列表 [英] append to a sublist appends to every sublist
问题描述
我正在编写一个包含 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屋!