Python:从数字int获取过去12个月的列表

时间:2018-09-10 13:47:59

标签: python

如果我有一个像6那样的月份整数,如何获得前12个月的名称?因此,传递6会给我一个类似

的列表
['June','May','April','March','February','January','December','November','October','September','August','July']

3 个答案:

答案 0 :(得分:1)

m =['January', 'February', 'March', 'April', 'May', 'June', 'July','August', 'September', 'October', 'November', 'December']
pos = 6 # current month is June
for i in range(pos,pos-12,-1):
    print(m[i-1]) # in real m[pos] == July . so m[pos-1] == June

答案 1 :(得分:0)

您可以使用itertools.cycle,跳过前一个x并从倒数月份列表中返回下一个12:

import itertools

def get_month_from_int(i):
  reverse_months = itertools.cycle([
  'December','November','October','September','August','July', 'June','May','April', 'March','February','January'
  ])
  for _ in range(i):
    next(reverse_months)
  return [next(reverse_months) for _ in range(12)]

这里有live example

答案 2 :(得分:0)

我知道它已经得到了回答,但是我认为使用日历模块还有更多的pythonic方式

import calendar

current = 11
last_12_months = [calendar.month_name[1:][i] for i in range(current - 12, current)] # starting from the last
reverse_last_12_months = reversed(last_12_months) # starting from the current