【问题标题】:Converting month numbers to month name using a dictionary in Python使用 Python 中的字典将月份数字转换为月份名称
【发布时间】: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


【解决方案1】:

尝试MonthDict[month_int] - 要访问字典的值,您需要使用方括号,而不是圆括号。

【讨论】:

  • 真是个愚蠢的错误,谢谢!更改为:for i in month_no: month_no = MonthDict[month_no] 导致“TypeError: unhashable type: 'numpy.ndarray'”
  • @J.Smith 试试MonthDict[i] - 您正在尝试使用整个month_no 数组作为字典键,而不是单个数字
  • 非常感谢。这已经解决了我的问题,现在进入下一个问题!谢谢!
【解决方案2】:

正如我在 cmets 中指出的那样,索引 dict 是 []
但是您也可以使用datetime 模块为您提供完整的月份名称(取决于区域设置),而无需创建自己的转换表,例如

In []:
import datetime
year_no, month_no = 2017, 3
d = datetime.datetime(year_no, month_no, 1)
d.strftime('%B')

Out[]:
'March'

或简称:

In []:
d.strftime('%b')

Out[]:
'Mar'

【讨论】:

  • 嘿,谢谢你的帮助。我设法使用@Chris Applegate 的回复解决了我的问题,但我也非常感谢。
猜你喜欢
  • 1970-01-01
  • 2012-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-07
  • 1970-01-01
  • 2016-10-04
相关资源
最近更新 更多