我正在尝试创建一个函数,可以将月份编号转换为缩写月份名称或将缩写月份名称转换为月份编号。我认为这可能是一个常见问题,但我无法在网上找到它。
我在想calendar模块。我看到要将月份编号转换为缩写月份名称,您只需执行 calendar.month_abbr[num]
。不过,我看不到另一个方向的方法。创建一个字典来转换另一个方向是处理这个问题的最好方法吗?或者有没有更好的方法从月份名称到月份编号,反之亦然?
最佳答案
使用 calendar
模块创建一个反向字典(与任何模块一样,您需要导入该模块):
{month: index for index, month in enumerate(calendar.month_abbr) if month}
在 2.7 之前的 Python 版本中,由于该语言不支持 dict 理解语法,您必须这样做
dict((month, index) for index, month in enumerate(calendar.month_abbr) if month)
关于python - 如何将月份名称映射到月份编号,反之亦然?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3418050/