gpt4 book ai didi

python - 在Python中使用对象作为键时索引哈希表

转载 作者:行者123 更新时间:2023-12-01 05:08:14 25 4
gpt4 key购买 nike

所以我有两个类“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

最佳答案

我怀疑您遇到的问题是您使用 key 实例中的字符串构建字典。然后,当您查找某个项目时,您将在 key 实例中使用整数。 "0" 不等于 Python 中的 0,因此您的查找失败。

尝试使用 qkey = key("1","1","16", 而不是 qkey = key(1,1,16,0,0,0) "0","0","0") 在您的测试代码中。

或者,您可能希望在首先创建时将字符串转换为整数和浮点值:

newkey = key(*map(int, part_list[:6]))         # first six values are ints
newvalue = value(*map(float, part_list[6:11])) # next five are floats

关于python - 在Python中使用对象作为键时索引哈希表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24682947/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com