[英]Saving multiple return values from a Python function
我有一個函數,經過一些計算后會返回4個值 。 我給出5個參數作為輸入。
我使用6個不同的輸入參數運行上述函數6次,以獲得6個不同的輸出。
def id_match(zcosmo,zphot,zmin,zmax,mlim):
data_zcosmo_lastz = zcosmo[(data_m200>mlim)*(zcosmo>zmin)*(zcosmo<zmax)]
data_zphot_lastz = zphot[(data_m200>mlim)*(zphot>zmin)*(zphot<zmax)]
halo_id_zcosmo = data_halo_id[(data_m200>mlim)*(zcosmo>zmin)*(zcosmo<zmax)]
halo_id_zphot = data_halo_id[(data_m200>mlim)*(zphot>zmin)*(zphot<zmax)]
idrep_zcosmo = data_idrep[(data_m200>mlim)*(zcosmo>zmin)*(zcosmo<zmax)]
idrep_zphot = data_idrep[(data_m200>mlim)*(zphot>zmin)*(zphot<zmax)]
file2freq1 = Counter(zip(halo_id_zcosmo,idrep_zcosmo))
file2freq2 = Counter(zip(halo_id_zphot,idrep_zphot))
set_a = len(set(file2freq1) & set(file2freq2)) # this has the number of common objects
difference = 100.0 - (set_a*100.0)/len(data_zcosmo_lastz)
print difference
return (len(data_zcosmo_lastz),len(data_zphot_lastz),set_a,difference)
zmin_limits = [0.1,0.4,0.7,1.0,1.3,1.6]
zmax_limits = [0.4,0.7,1.0,1.3,1.6,2.1]
mlim_limits = [5e13,5e13,5e13,5e13,5e13,5e13]
for a,b,c in zip(zmin_limits,zmax_limits,mlim_limits):
id_match(data_zcosmo_lastz,data_zphot_lastz,a,b,c)
上面的代碼為6個不同的輸入參數中的每個輸出difference
。
但是我想知道如何將函數的輸出保存到數組中,以便將其保存為csv file
?
我知道這樣做
a,b,c,d = id_match(input params)
將給a,b,c,d
具有id_match
的輸出之一。 但是我想將所有返回值存儲在單個數組中。
id_match()
已經返回一個元組。 您不需要將其轉換為任何東西,因為csv.DictWriter.writerow()
可以處理一個元組。 您所需要做的就是為id_match()
返回的值分配一個變量,並將其寫入一個csv
文件:
with open(myfilename, 'w') as csvfile:
writer = csv.DictWriter(csvfile)
for a,b,c in zip(zmin_limits,zmax_limits,mlim_limits):
info = id_match(data_zcosmo_lastz,data_zphot_lastz,a,b,c)
writer.writerow(info)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.