我有一个程序,生成一个非常大的浮点数序列,通常是数千万左右。我需要一个很好的方法把它们保存在一个文件里。我将按顺序编写它们,并使用Python阅读它们。浮点数在一个一维数组中,如下所示:
[39534.543, 834759435.3445643, 1.003024032, 0.032543, 434.0208...]
(这些数字都是例子,我只是用键盘来制造它们。)
生成数字的代码:
for x in range(16384):
for y in range(16384):
float = <equation with x and y>
<write float to file>
发布于 2020-02-10 12:28:05
可以使用struct.pack
函数将浮点数存储为64位双倍:
from struct import pack, unpack
array = [39534.543, 834759435.3445643, 1.003024032, 0.032543, 434.0208]
with open('store', 'wb') as file:
file.write(pack('d' * len(array) , *array))
以便以后可以使用struct.unpack
检索数组的值。
with open('store', 'rb') as file:
packed = file.read()
array = unpack('d' * (len(packed) // 8), packed) # 8 bytes per double
发布于 2020-02-10 13:08:16
你的一些数字看起来太短了,不可能是随机的。因此,您可以通过压缩将它们存储在每个浮动中的小于8个字节。例如:
商店:
import lzma
array = [39534.543, 834759435.3445643, 1.003024032, 0.032543, 434.0208]
with open('store', 'wb') as file:
file.write(lzma.compress(repr(array).encode()))
负载:
import lzma, ast
with open('store', 'rb') as file:
array = ast.literal_eval(lzma.decompress(file.read()).decode())
print(array)
即使有随机数据,我平均得到的字节也不到8个字节:
>>> n = 10**5
>>> a = [random.random() for _ in range(n)]
>>> len(lzma.compress(repr(a).encode())) / n
7.98948
诚然,这是相当缓慢的,但至少对我的随机数据。对于非随机数据来说可能更快。或者尝试一个较低的压缩水平或其他压缩。pickle
模块还提到了压缩,因此这可能值得一试。
https://stackoverflow.com/questions/60157757
复制