gpt4 book ai didi

以变​​量为键的 Python 字典

转载 作者:太空狗 更新时间:2023-10-29 21:17:47 27 4
gpt4 key购买 nike

我是一名 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 教程阅读时间)。这是个好主意吗?

在尝试使用字典执行此操作时,我决定将字节数作为“键”,将计数器作为“值”。我的计划是在每次出现 key 时增加计数器。截至目前,我的代码片段如下:

# 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”调用中遇到语法错误,这让我怀疑是否可以将变量用作字典键。到目前为止我看到的所有示例都假设 key 是预先可用的。就我而言,只有在解析输入文件时我才能获得我的 key 。

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

感谢您提供的任何帮助。

最佳答案

学习一门语言不仅要学习标准库,还要学习语法和基本类型。 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"

关于以变​​量为键的 Python 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8293617/

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