追加到子列表追加到每个子列表 [英] append to a sublist appends to every sublist
问题描述
我写了一组10桶列出一个简单的哈希表。该指数是使用内置的散列()
计算,然后模表的大小。然而,当我尝试的对象遗愿清单追加的索引,它被附加到每一桶列表,而不是。
我试着定义add_HT不同的方式,但我不断收到同样的效果。我在做什么错了?
尺寸= 10
HT = [[]] *尺寸高清add_HT(数据):
指数=散列(数据)大小%
HT [指数] .append(数据)打印HT[] [] [] [] [] [] [] [] [] []add_HT('你好')['你好'],['你好'],['你好'],['你好'],['你好'],['你好'],['你好'],['你好'],[ '你好你好']]
HT = [[]] *尺寸
,使尺寸
指针同一个列表。 add_HT
不是这里的问题。您需要定义 HT
为 []因我的xrange(大小)]
。
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
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屋!