【发布时间】:2018-06-11 17:15:19
【问题描述】:
我正在尝试将一组数字 (1-12) 转换为相应的月份(1 月至 12 月),但是我必须使用字典。
我有几个月的数组形式,我收到错误“TypeError:只有长度为 1 的数组可以转换为 Python 标量”或“TypeError:'dict' 对象不可调用”
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']
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()
所有这些代码都有效,所以它只是为了上下文。接下来是我正在苦苦挣扎的部分
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"
}
我尝试过使用:
month_int=int(month_no)
month=MonthDict(month_int)
但我只是得到长度为 1 的错误。
我也尝试过:
for integer in month_no:
month_no = MonthDict(month_no)
但这会产生“dict object not callable”错误
【问题讨论】:
-
Dict 的索引是
[]而不是() -
考虑 str.format 来配置您的输出。
标签: python arrays python-3.x numpy dictionary