因此,我尝试使用Python calendar API遍历一年中的几个月。假设当前月份为一月(月份“ 1”)。如果我执行calendar.month_name[1-1](一月前的一个月),则得到的结果是空字符串""-似乎是因为月份“ 0”不存在。但是,如果我执行calendar.month_name[1-2],则生成的-1值会导致返回December

所以我的问题是如何获取month_name[]0参数以返回前一个月?

最佳答案

一种方法是使用列表推导将月份存储在新变量中

months = [month for month in calendar.month_name if month]


从这里您应该可以看到

>>> months[0]
January
>>> months[11]
December
>>> months[-1]
December


编辑1:
为了回答您的评论,您可以使用库itertools

import calendar
from itertools import cycle
months = [month for month in calendar.month_name if month]

pool = cycle(months[::-1]) # creating a cyclic pool of the reverse list

for month in pool:
    print(month)


输出:

December
November
October
September
August
July
June
May
April
March
February
January
December
November
October
September
August
July
June
May
April
March
February
January
June
May
April
December
November
October
September
August
July
June
May
April
...


编辑2:

甚至更简单的方法可能是重新计算索引,例如

import calendar
months = [month for month in calendar.month_name if month]

old_index = -4003

new_index = old_index % len(months)

print(new_index, months[new_index])


输出:

5 June

关于python - Python calendar.month_name如何跳过0索引,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47059165/

10-15 00:49