因此,我尝试使用Python calendar
API来循环查看一年中的几个月。假设当前月份是1月(月份“1”)。如果我calendar.month_name[1-1]
(1月前一个月),我得到的结果是一个空字符串""
- 似乎因为月份“0”不存在。但是,如果我执行calendar.month_name[1-2]
,则生成的-1
值会导致December
返回。
所以我的问题是如何获得month_name[]
0
参数返回前一个月?
答案 0 :(得分:2)
一种方法是使用列表推导将月份存储在新变量中
template1
从这里你应该可以看到
months = [month for month in calendar.month_name if month]
编辑1:
作为评论的答案,您可以使用库>>> months[0]
January
>>> months[11]
December
>>> months[-1]
December
。
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)
编辑2:
更简单的方法是重新计算索引,例如
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
...
输出:
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])