簡體   English   中英

將行向量附加到 python 中保存的數組

[英]Appending row vector to saved array in python

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

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

我如何 append 這些行,一次一個(或以預定義的塊大小)到保存到文件(例如使用 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-writing-data
https://docs.h5py.org/en/stable/high/dataset.html#resizable-datasets

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM