Python文件内存优化集

2024-03-29 06:50:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python很陌生。在python脚本中,我需要检查输入字符串是否存在于“titles”集合中;我从文件“titles”中以换行分隔的字符串加载该集合。它消耗大量内存。我选择存储在set中,因为后面还有if inputstring in titles:。你知道吗

Line #    Mem usage    Increment   Line Contents
================================================
     1    6.160 MiB    0.000 MiB   @profile
     2                             def loadtitles():
     3  515.387 MiB  509.227 MiB     titles = open('titles').read().split()
     4  602.555 MiB   87.168 MiB     titles = set(titles)

第一季度。有没有其他对象类型的内存效率更高来存储这些大数据?

我能想到的一个解决方案是,如果我将文件作为字符串加载,它消耗的内存与filesize完全相同;这是100%的最佳内存消耗。你知道吗

Line #    Mem usage    Increment   Line Contents
================================================
     1    6.160 MiB    0.000 MiB   @profile
     2                             def loadtitles():
     3  217.363 MiB  211.203 MiB     titles = open('titles').read()

然后我可以做if inputstring+'\n' in titles:

第2季度。有没有更快的替代方法?


Tags: 内存字符串iniflinecontentsusageprofile
2条回答

您可以:

  • 如果要查找大量键,请使用键/值存储。你知道吗
  • 如果要查找的键很少,则逐行遍历文件并检查是否存在键。你知道吗

迭代文件(逐行处理)而不是读取文件的全部内容将减少内存消耗。(与生成器表达式结合使用):

def loadtitles():
    with open('titles') as f:
        titles = {word for line in f for word in line.split()}

相关问题 更多 >