用变量作为键的Python字典

7 投票
4 回答
3566 浏览
提问于 2025-04-17 07:12

我是一名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'调用中遇到了语法错误,这让我开始怀疑是否可以使用变量作为字典的键。我看到的所有示例都假设键是事先已知的。而在我的情况下,我只能在解析输入文件时才能获得我的键。

(请注意,我的输入文件可能有成千上万行,并且有数百个不同的键)

谢谢你提供的任何帮助。

4 个回答

4

在字典中,dict.has_key()这个方法在Python 3中已经不见了,取而代之的是使用关键字 in:

if numBytes in allocationList:    # do not use numBytes as a string, use the variable directly
    #do the stuff

不过在你的情况下,你也可以用一行代码来替代所有的

if allocationList.has_key('numBytes')
            currentCount = allocationList['numBytes']
            currentCount += 1
            allocationList['numBytes'] = currentCount
        else
            allocationList['numBytes'] = 1 

,可以使用get方法:

allocationList[numBytes] = allocationList.get(numBytes, 0) + 1
4

你遇到语法错误是因为这一行的末尾缺少了冒号:

if allocationList.has_key('numBytes')
                                     ^

你的方法没问题,但使用 dict.get() 并设置一个默认值可能会更简单:

allocationList[numBytes] = allocationList.get(numBytes, 0) + 1

因为你的 allocationList 是一个字典,而不是列表,所以你可能想给这个变量换个名字。

10

学习一门编程语言,不仅要了解语法和基本的数据类型,还要熟悉它的标准库。Python 里有一个类可以让你的工作变得非常简单,那就是 collections.Counter

from collections import Counter

with open("allocFile.txt") as fp:
    counter = Counter(line.split()[0] for line in fp)

for bytes, count in counter.most_common():
    print bytes, "bytes -> ", count, " times"

撰写回答