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

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

问题描述

我写了一组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屋!

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