将行向量追加到python中保存的数组中



我正在循环中生成行向量。例如:

import random
for x in range(100):
print([random.randint(0,10), random.randint(0,10), random.randint(0,10)])

如何将这些行一次一行(或以预定义的块大小(附加到保存到文件中的(最初为空(数组中(例如,使用HDF5或类似方法(?我知道数组需要的列数,但不知道最终数组会有多少行。

import random
vec_array = []
for x in range(100):
row = [random.randint(0,10), random.randint(0,10), random.randint(0,10)]
print(row)
vec_array.append(row)
print(vec_array)

我不知道你说的";保存的数组";。你要把这个数组导出到什么地方?要将此数组保存在JSON中,可以使用:

import json
with open('output.json','w+') as f:
json.dump({'vec_array':vec_array},f)

要再次加载数据,只需运行:

import json
with open('output.json') as f:
vec_array = json.load(f)['vec_array']

进一步阅读:
https://docs.python.org/3/library/json.html

对于更大的数据集,SQL数据库将是合适的:
https://docs.python.org/3/library/sqlite3.html

如果您确定要使用HDF5,那么如果超过最大大小,则必须调整数据集的大小
https://docs.h5py.org/en/stable/high/dataset.html#reading-写入数据
https://docs.h5py.org/en/stable/high/dataset.html#resizable-数据集

最新更新