Python字典,变量作为键

Gau*_*tam 7 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    
Run Code Online (Sandbox Code Playgroud)

我的第一个目标是创建一个表来计算特定数量的字节分配的实例.换句话说,我对上面输入的所需输出将是这样的:

48 bytes -> 3 times
96 bytes -> 1 times
24 bytes -> 2 times
Run Code Online (Sandbox Code Playgroud)

(现在,我不关心内存地址)

由于我正在使用Python,我认为使用字典这样做是正确的方法(基于大约3个小时的阅读Python教程).这是一个好主意吗?

在尝试使用字典时,我决定将字节数设为'key',将计数器设为'value'.我的计划是在每次出现钥匙时递增计数器.截至目前,我的代码段如下:

# 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"
Run Code Online (Sandbox Code Playgroud)

有了这个,我在'has_key'调用中得到一个语法错误,这让我质疑是否甚至可以将变量用作字典键.到目前为止我看到的所有示例都假设密钥可以预先获得.在我的情况下,我只有在解析输入文件时才能获取密钥.

(请注意,我的输入文件可以运行成数千行,包含数百个不同的键)

感谢您提供任何帮助.

Pet*_*rin 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"
Run Code Online (Sandbox Code Playgroud)

  • +1:如果你只对计数感兴趣,那么`Counter`就是你要走的路.另一方面,OP写道:*现在,我并不关心内存地址*---我想他迟早需要一个超越"Counter"的自定义解决方案. (2认同)