python中的月份名称到月份编号,反之亦然 [英] month name to month number and vice versa in python

查看:56
本文介绍了python中的月份名称到月份编号,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个函数,该函数可以将月份数字转换为月份缩写名称或将月份缩写名称转换为月份数字.我认为这可能是一个常见问题,但我在网上找不到.

I am trying to create a function that can convert a month number to an abbreviated month name or an abbreviated month name to a month number. I thought this might be a common question but I could not find it online.

我在考虑 calendar 模块.我看到要将月份数字转换为缩写月份名称,您只需执行 calendar.month_abbr[num].不过,我看不到另一个方向.创建用于转换另一个方向的字典是处理此问题的最佳方法吗?或者有没有更好的方法从月份名称到月份编号,反之亦然?

I was thinking about the calendar module. I see that to convert from month number to abbreviated month name you can just do calendar.month_abbr[num]. I do not see a way to go the other direction though. Would creating a dictionary for converting the other direction be the best way to handle this? Or is there a better way to go from month name to month number and vice versa?

推荐答案

使用 calendar 模块创建反向字典(与任何模块一样,您需要导入):

Create a reverse dictionary using the calendar module (which, like any module, you will need to import):

{month: index for index, month in enumerate(calendar.month_abbr) if month}

在 2.7 之前的 Python 版本中,由于该语言不支持 dict comprehension 语法,您将不得不这样做

In Python versions before 2.7, due to dict comprehension syntax not being supported in the language, you would have to do

dict((month, index) for index, month in enumerate(calendar.month_abbr) if month)

这篇关于python中的月份名称到月份编号,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆