【问题标题】:Converting a list of int to a list of string takes too much memory in Python将 int 列表转换为字符串列表在 Python 中占用太多内存
【发布时间】:2022-01-03 11:10:41
【问题描述】:

我需要将整数存储为字符串。例如。 - [1,2,3] 将存储为 '1;2;3'。为此,我需要首先将整数列表转换为字符串列表。但是这种转换的内存使用量很大。

显示问题的示例代码。

from sys import getsizeof
import tracemalloc

tracemalloc.start()

curr, peak = tracemalloc.get_traced_memory()
print((f'Current: {round(curr/1e6)} MB\nPeak: {round(peak/1e6)} MB'))

print()

list_int = [1]*int(1e6)

curr, peak = tracemalloc.get_traced_memory()
print((f'Current: {round(curr/1e6)} MB\nPeak: {round(peak/1e6)} MB'))
print(f'Size of list_int: {getsizeof(list_int)/1e6} MB')

print()

list_str = [str(i) for i in list_int]

curr, peak = tracemalloc.get_traced_memory()
print((f'Current: {round(curr/1e6)} MB\nPeak: {round(peak/1e6)} MB'))
print(f'Size of list_str: {getsizeof(list_str)/1e6} MB')

输出:

Current: 0 MB
Peak: 0 MB

Current: 8 MB
Peak: 8 MB
Size of list_int: 8.000056 MB

Current: 66 MB
Peak: 66 MB
Size of list_str: 8.448728 MB

两个列表占用的内存差不多(8 MB),但程序在转换过程中使用的内存很大(66 MB)。

如何解决这个内存问题?

编辑:我需要将它转换为字符串,所以最后我会运行';'.join(list_str)。所以,即使我使用生成器/迭代器,比如说list_str = map(str, list_int),内存使用情况也是一样的。

【问题讨论】:

  • 我不知道为什么会这样,但是使用可迭代对象怎么样?例如,list_str = map(str, list_int)。这不会存储整个字符串列表,因此您可以使用更少的内存。
  • @j1-lee 是的,但是正如我提到的,我的最终目标是创建一个字符串,所以当我运行';'.join(list_str) 时,使用你提到的可迭代,内存使用量变得相同.
  • 啊,你是对的。
  • @aniketsharma00411 与列表理解相比,生成器内存使用量将太少。请参阅下面的答案。
  • @TimRoberts 66MB 并不大,但是当我在我的应用程序中运行类似的东西时,大小为 60 MB 的 list_str 的内存消耗为 560+ MB,这会使我的服务器崩溃。我展示的代码只是一个例子。

标签: python python-3.x string list


【解决方案1】:

改用 Numpy。试试这个

from sys import getsizeof
import tracemalloc
import numpy as np

tracemalloc.start()

arr = np.ones((1000000,), dtype=np.str)
for i in [1]*int(1e6):
    arr[i] = str(i)

curr, peak = tracemalloc.get_traced_memory()
print((f'Current: {round(curr/1e6)} MB\nPeak: {round(peak/1e6)} MB'))
print(f'Size of list_str: {getsizeof(list(arr))/1e6} MB')

我认为有一点改进的输出

Current: 4 MB
Peak: 12 MB
Size of list_str: 9.000112 MB

【讨论】:

  • @j1-lee 是的,你是对的。我现在会更正它。
  • @j1-lee used dtype=np.str now 现在数组元素是字符串
  • 在这种情况下,';'.join(arr) 也会增加内存使用量。
猜你喜欢
  • 1970-01-01
  • 2018-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-12
  • 2016-04-14
相关资源
最近更新 更多