gpt4 book ai didi

Python calendar.month_name 如何跳过 0-index

转载 作者:太空宇宙 更新时间:2023-11-04 02:39:08 25 4
gpt4 key购买 nike

所以我尝试使用 Python calendar API 来循环一年中的几个月。假设当前月份是一月(月份“1”)。如果我执行 calendar.month_name[1-1](一月之前的一个月),我得到的结果是一个空字符串 "" - 似乎是因为月份“0”没有'存在。但是,如果我执行 calendar.month_name[1-2],生成的 -1 值将导致返回 December

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

最佳答案

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

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 calendar.month_name 如何跳过 0-index,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47059165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com