返回几个月前开始的月份数字列表

时间:2019-02-06 12:13:32

标签: python

从当前月份开始的3个月内,您将如何获得12个月数字的列表?例如:

当前月份为2月= 2(月份号)

所以3个月前是11月= 11(月数)

因此列表应为[11、12、1、2、3、4、5、6、7、8、9、10]

我已经完成:

month_choices = deque([1, 2,3,4,5,6,7,8,9,11,12])
month_choices.rotate(4)

3 个答案:

答案 0 :(得分:4)

用户可以指定当前月份吗?

如果是这样:

current_month = 2

[(i - 4) % 12 + 1 for i in range(current_month, current_month + 12)]

否则,将第一行替换为以下内容:

current_month = int(datetime.datetime.today().strftime('%m'))

也就是说,最好将datetime.timedelta用于任何形式的日期处理。

答案 1 :(得分:0)

l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
def fun(current_month,month_back):
    a=[]
    index = l.index(current_month)
    a=l[index-month_back:]+l[:index-month_back] # list slicing take the values from month back to the end of year and from the start of the list to month back 
    return a
print(fun(2,3))
# output : [11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

答案 2 :(得分:0)

如果您真的想旋转数组,通常有两种方法可以做到这一点。第一个是pythonic,涉及将列表的末尾附加到最前面。第二种方法是利用集合库并旋转包裹在双端队列对象中的列表。

''' Rotate an array of elements
'''

from collections import deque
from datetime import datetime

# Approach #1
def rotate_1(arr, amount):
    return arr[amount:] + arr[:amount]  # append the front of the list to the back

# Approach #2
def rotate_2(arr, amount):
    shifted = deque(arr)                # wrap list in an deque
    shifted.rotate(amount * -1)         # rotate normally works left-to-right
    return list(shifted)                # unwrap the list

months = list(range(1, 13))             # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

if __name__ == '__main__':
    offset = datetime.now().month - 1   # 1 (curent month indexed at 0)
    months = rotate_2(months, offset)   # [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1]
    months = rotate_2(months, -3)       # [11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    print(months)