【发布时间】:2014-09-01 04:57:18
【问题描述】:
所以我有“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
【问题讨论】:
-
它适用于我使用你的虚拟值(5、3、16、0、0、0)。您确定“report.txt”中实际上有一个带有这些值的键吗?您能否提供一个独立的示例,其中包含说明问题的示例数据?
-
是的,我确定这个值存在,一个非常简单的文件看起来像这样:(我将它添加到问题中)
-
首先,您不需要在课程开始时需要有趣的变量。这些不是“默认值”,而是类变量。更改一个将为 all 实例更改它。如果您想要默认值,请使用 def __init__(self, a=-1, b=-1) 等等。
-
不管怎样,你可以使用 collections.namedtuple 来代替这些类来返回一个简单的哈希类型。
-
'-1's 仅用于调试,它们并不重要。我对如何使它与对象一起工作感兴趣?