[英]Saving a multi-dimensional list in a file Python
我以這種方式創建了這個列表 bhs:
#Alotting Black Holes at z=6
bhs=[0]*1000
for i in tqdm(range(0,1000),position=0, leave=True):
if len(mass_array1[i])!=0:
bhs[i]=np.zeros(len(mass_array1[i]))
else:
bhs[i]=np.zeros(1)
for j in range (len(mass_array1[i])):
bhs[i][j]=np.random.lognormal(np.log(MbhthShimasaku(mass_array1[i],6)[j]),np.log(5))
我需要將結果保存在文本文件中。 我試過 numpy.savetxt、pickle.dump 和 open():
打開()
with open("bhs.txt", 'w') as file:
for row in bhs:
s = " ".join(map(str, row))
file.write(s+'\n')
#Result .txt file:
0.0
0.0
0.0
0.0
1937651.7861915156 246221.20328840986 226756.87389065413
0.0
0.0
numpy.savetxt()
bhs=np.array(bhs)
np.savetxt('bhs.txt',bhs,fmt='%s')
#Result .txt file:
[0.]
[0.]
[0.]
[0.]
[26447480.89508711 1097038.92200952 971383.67441455]
[0.]
[0.]
[0.]
[0.]
[0.]
泡菜
bhs.append(bhs)
tupleA=tuple(bhs)
filename = 'bhs.p'
with open(filename, 'wb') as filehandler:
pickle.dump(tupleA, filehandler)
#Result .p file
array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([1937651.78619152, 246221.20328841, 226756.87389065])
我無法從所有這些保存的文件中取回原始數組/列表。 當我嘗試使用這些加載列表中的任何一個時,我會收到某種錯誤:
np.loadtxt
could not convert string to float: '[0.]'
打開()
my_file = open("bhs.txt", "r")
content = my_file.read()
content_list = content.split(",")
my_file.close()
print(content_list)
[0.]\n[0.]\n[26447480.89508711 1097038.92200952 971383.67441455]\n[0.]\n[0.]\n[0.]\n[0.]\n[0.]\n[0.]\n[0.]\n[0.]\n
作為列表的 bhs 樣本
array([1461403.98258597]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([0.]), array([26447480.89508711, 1097038.92200952, 971383.67441455]),
我怎樣才能說出我的多維列表,以便我可以准確地回到我開始時的內容?
額外:mass_array1 文件
https://drive.google.com/file/d/1Kdmv1fcbDelEzGmi4BOE4HjUbM7Cg23b/view?usp=sharing
這就是我將它導入 python 的方式:
您需要先將文件解壓縮到一個文件夾中。
dirlist=["bh2e10"]
import time
mass_array1=[0]*1000
#print(mass_array)
#read all the files
for i,X in enumerate(dirlist):
exec('filelist=glob.glob("%s/test*.dat")'%(X))
#exec("mass_array%s=[]"%X)
initial_mass=[]
for j,Y in tqdm(enumerate(filelist),position=0, leave=True, total=1000):
Y=Y.replace(os.sep, '/')
#Z=int(Y[10:13])
Z=int(re.findall("\d+", Y)[2])
#print(Z)
mass_array1[Z]=[]
#print('i=',Z,end="\r")
#print('i=',Z,end="\r")
exec("initial_partial=np.loadtxt('%s',max_rows=1)"%(Y))
exec("initial_mass=np.append(initial_mass,initial_partial)")
exec("mass_partial=np.loadtxt('%s',skiprows=1)"%(Y))
mass_array1[Z]=np.append(mass_partial,mass_array1[Z])
#mass_array1[Z]=mass_partial
使用csv
模塊
import numpy as np
import csv
bhs = [[0.], [0.], [0.], [0.], [26447480.89508711, 1097038.92200952, 971383.67441455], [0.], [0.], [0.], [0.], [0.]]
# write to csv
with open("bhs.txt", mode="w", newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(bhs)
# read from csv
with open("bhs.txt", mode="r") as csvfile:
reader = csv.reader(csvfile)
bhs1 = [np.array(row, dtype=np.float).tolist() for row in reader]
>>> bhs == bhs1
True
更新:使用joblib
import joblib
bhs = [[0.], [0.], [0.], [0.], [26447480.89508711, 1097038.92200952, 971383.67441455], [0.], [0.], [0.], [0.], [0.]]
joblib.dump(bhs, "bhs.txt")
bhs1 = joblib.load("bhs.txt")
>>> bhs == bhs1
True
首先,了解您創建的內容:
In [94]: bhs = [0]*5
In [95]: bhs[1]=np.random.rand(4)*1000
In [96]: bhs
Out[96]: [0, array([900.04634682, 67.58574156, 364.69588687, 868.10145473]), 0, 0, 0]
這是一個列表,大部分為 0,以及一個或多個 1d arrays。
csv
文件格式用於“表格”,許多行都具有相同的列數。
savetxt
寫入一個數組,最好是 2d,但它可以與 1d 一起使用。 但是你給了它一個清單。 所以它必須先制作一個數組:
In [98]: np.array(bhs)
<ipython-input-98-fe2575327968>:1: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
np.array(bhs)
Out[98]:
array([0, array([900.04634682, 67.58574156, 364.69588687, 868.10145473]),
0, 0, 0], dtype=object)
用%s
保存的結果是:
In [99]: cat bhs.txt
0
[900.04634682 67.58574156 364.69588687 868.10145473]
0
0
0
該數組元素被寫入str
顯示。 使用csv
工具很難加載這樣的文件,盡管並非不可能。 它不是正確的 csv 文件。
pickle
幾乎可以處理任何 python object,包括各種東西的列表:
In [102]: with open('bhs.p','wb') as f:
...: pickle.dump(bhs, f)
...:
In [105]: with open('bhs.p','rb') as f:
...: new=pickle.load(f)
...:
...:
In [106]: new
Out[106]: [0, array([900.04634682, 67.58574156, 364.69588687, 868.10145473]), 0, 0, 0]
Out[98] 中列表的數組版本也可以保存為數組(帶有嵌入式酸洗):
In [110]: np.save('foo.npy',_98)
In [111]: np.load('foo.npy', allow_pickle=True)
Out[111]:
array([0, array([900.04634682, 67.58574156, 364.69588687, 868.10145473]),
0, 0, 0], dtype=object)
我懷疑你是否真的想要或應該像這樣創建一個 arrays 列表。 無論如何,在嘗試保存隨機選擇的格式之前,請確保您了解您創建的內容。
您最好將其保存在 a.csv (逗號分隔文件,以便您可以輕松上傳或獲取它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.