在Python中使用对象作为键时如何为哈希表建立索引
我有两个类,一个叫“key”(键),另一个叫“value”(值),我的想法是用它们来创建一个哈希表。
class key:
num_master = -1
num_slave = -1
width = -1
num_pipeline = -1
diff_clock_master = -1
diff_clock_slave = -1
def __init__(self,m,s,w,p,dm,ds):
self.num_master = m
self.num_slave = s
self.width = w
self.num_pipeline = p
self.diff_clock_master = dm
self.diff_clock_slave = ds
def __hash__(self):
return hash((self.num_master,self.num_slave,self.width,self.num_pipeline,self.diff_clock_master,self.diff_clock_slave))
def __eq__(self,other):
return (self.num_master,self.num_slave,self.width,self.num_pipeline,self.diff_clock_master,self.diff_clock_slave) == (other.num_master,other.num_slave,other.width,other.num_pipeline,other.diff_clock_master,other.diff_clock_slave)
class value:
alms = -1
brams = -1
labs = -1
freq = -1
power = -1
def __init__(self,a,b,l,f,p):
self.alms = a
self.brams = b
self.labs = l
self.freq = f
self.power = p
我这样来填充哈希表:
def parsify(report_name):
report = open(report_name,'r')
for line in report:
#split line
part_list = line.split()
newkey = key(part_list[0],part_list[1],part_list[2],part_list[3],part_list[4],part_list[5])
newvalue = value(part_list[6],part_list[7],part_list[8],part_list[9],part_list[10])
hash_table[newkey]=newvalue
return hash_table
然后我尝试像这样访问哈希表:
#test
hash_table = parsify('report.txt')
qkey = key(1,1,16,0,0,0)
print hash_table[qkey].alms
但是这样不行。我该如何访问这个哈希表呢?有没有什么方法可以让这个过程更简单一些?
这是一个示例的 report.txt 文件:
1 1 16 0 0 0 102.0 0.0 10.2 300.75 1.36 m1_s1_w16_p0_dcm0_dcs0_traffic_0_----->_m1_s1_w16_p0_dcm0_dcs0_traffic_0
1 1 16 1 0 0 102.0 0.0 10.2 300.75 1.36 m1_s1_w16_p1_dcm0_dcs0_traffic_0_----->_m1_s1_w16_p1_dcm0_dcs0_traffic_0
1 1 16 2 0 0 102.0 0.0 10.2 300.75 1.36 m1_s1_w16_p2_dcm0_dcs0_traffic_0_----->_m1_s1_w16_p2_dcm0_dcs0_traffic_0
1 1 16 3 0 0 166.0 0.0 16.6 303.03 2.02 m1_s1_w16_p3_dcm0_dcs0_traffic_0_----->_m1_s1_w16_p3_dcm0_dcs0_traffic_0
2 个回答
0
你可以通过使用元组作为字典的键来简化这个过程,而不是使用自定义类。例如,你创建键的方式是这样的:
key(1,1,16,0,0,0)
那么这里你完全可以用一个简单的元组来代替
(1,1,16,0,0,0)
在读取数据的时候也是一样:
tuple(part_list[:6])
元组是字典的好键,这样你就不需要担心类的问题了。值也可以逻辑上存储为元组。或者你有特别的理由需要更复杂的结构吗?
2
我怀疑你遇到的问题是,你在创建字典的时候用的是字符串作为key
的值。但是当你去查找某个项目时,却用的是整数作为key
的值。在Python中,"0"
和0
是不一样的,所以你的查找失败了。
你可以试试把qkey = key(1,1,16,0,0,0)
改成qkey = key("1","1","16","0","0","0")
,这样在测试代码中就能正常工作了。
或者,你也可以在一开始创建key
和value
的时候,把字符串转换成整数和浮点数:
newkey = key(*map(int, part_list[:6])) # first six values are ints
newvalue = value(*map(float, part_list[6:11])) # next five are floats