将月数转换为天数

时间:2018-01-03 17:53:11

标签: python dictionary

我有一个.npz文件,我已经从.txt文件中读取数据并将其转换为表格。 table

数据附带与每个值相关联的月份。我必须使用字典将这些数字转换为书面月份(1月=​​ 1,2月2日= 2等)。

然而,当我这样做时,表格会在12月份更改为列表 changes to list just december

我的代码:

import numpy as np

outfile = ("heathrow_weather.npz")

#find out names of arrays
ph_read= np.load(outfile)
print(ph_read.files)

#assign arrays to a variable
max_temp=ph_read['t_max']

month_no=ph_read['month']

year_no=ph_read['year']

rainfall=ph_read['rainfall']

min_temp=ph_read['t_min']


#working marks

MonthDict={ 1 : "January",
       2 : "February",
       3 : "March",
       4 : "April",
       5 : "May",
       6 : "June",
       7 : "July",
       8 : "August",
       9 : "September",
       10 : "October",
       11 : "November",
       12 : "December"
}


for i in month_no:
    month_no = MonthDict[i]

#print(month_no) produces only "december"

outfile = open("weather_tables.txt", "w")
outfile.write("Month    Year    Min Temp    Max Temp    Rainfall\n")
outfile.write("                   (°C)         (°C)         (mm)\n")


for t0, t1, t2, t3, t4 in zip(month_no, year_no, max_temp, min_temp, rainfall):

    string = str(t0)+"      "+str(t1)+"        "+str(t2)+"          "+str(t3)+"         "+str(t4)+"\n"
    outfile.write(string)

outfile.close()

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

每次循环时,for i in month_no循环只是覆盖month_no,而不是创建与原始month_no数组中的月份名称对应的所有月份名称的列表。使用列表理解。

month_no = [monthDict[i] for i in month_no]