我是一个Python新手,试图解析一个文件来创建一个内存分配表。我的输入文件格式如下:变量作为键的Python字典
48 bytes allocated at 0x8bb970a0
24 bytes allocated at 0x8bb950c0
48 bytes allocated at 0x958bd0e0
48 bytes allocated at 0x8bb9b060
96 bytes allocated at 0x8bb9afe0
24 bytes allocated at 0x8bb9af60
我的第一个目标是创建一个表来计算特定数量的字节分配的实例。换句话说,我所希望的上述输入输出会是这样的:
48 bytes -> 3 times
96 bytes -> 1 times
24 bytes -> 2 times
(现在,我不关心的内存地址)
由于我使用Python,我想使用字典做这件事将是正确的方式(基于大约3小时的阅读Python教程)。这是一个好主意吗?
在试图使用字典来做到这一点时,我决定将字节数作为'键',并将计数器作为'值'。我的计划是每发生一次密钥都要增加计数器。截至目前,我的代码片段如下:
# Create an empty dictionary
allocationList = {}
# Open file for reading
with open("allocFile.txt") as fp:
for line in fp:
# Split the line into a list (using space as delimiter)
lineList = line.split(" ")
# Extract the number of bytes
numBytes = lineList[0];
# Store in a dictionary
if allocationList.has_key('numBytes')
currentCount = allocationList['numBytes']
currentCount += 1
allocationList['numBytes'] = currentCount
else
allocationList['numBytes'] = 1
for bytes, count in allocationList.iteritems()
print bytes, "bytes -> ", count, " times"
有了这个,我在“对象的has_key”出现语法错误调用,这使我怀疑它是否是可以使用变量作为字典键。迄今为止我所见过的所有例子都假设密钥可用。在我的情况下,我只能在解析输入文件时才能得到我的密钥。
(请注意,我输入文件可以运行到千行,用数百种不同的键)
感谢您的帮助,您可以提供。
,我看到你报“的numBytes”,所以,你总是指不断 – dmitry
和你行后'如果allocationList.has_key(“的numBytes”)'和'else'省略冒号 - 它应该是语法错误 – dmitry