【问题标题】:Print all period in between two periods in Python在 Python 中打印两个句点之间的所有句点
【发布时间】:2017-05-26 22:12:17
【问题描述】:

假设我的期间是NOV-2016MAR-2018,我需要打印介于(NOV-2016, DEC-2016, JAN-2017MAR-2018) 之间的所有期间。可以做些什么来获得想要的结果。现在我这样做了,但我没有得到想要的结果:

start_period = 'NOV-2017'
end_period = 'JUN-2019'
array = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']
year1 = int(start_period.split('-')[1])
year2 = int(end_period.split('-')[1])
diff = year2-year1
month_start = start_period.split('-')[0]
month_end = end_period.split('-')[0]
index1 = array.index(month_start)
index2 = array.index(month_end)
while diff>0:
    while(diff>=1 and (index2+1) != index1):
        if(index1==12):
            index1 = 0
        print(array[index1])
        index1+=1
    diff-=1
    if diff==0:
        break

【问题讨论】:

  • 你得到的结果是什么?
  • 11 月 12 月 1 月 2 月 3 月 4 月 5 月 6 月
  • 但我还应该从 2018 年和 2019 年从 7 月得到另一个输出到 6 月
  • diff>0 更改为 diff>=0。因为您还想处理期间为同一年的情况。

标签: python


【解决方案1】:

我认为,如果您每年都进行迭代,那么处理您的问题会更容易。在每年年底将月份重置为 JAN。每年检查您是否在最后一年,然后设置适当的结束月份。

这是一个例子:

start_period = 'NOV-2017'
end_period = 'JUN-2019'
months = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']

def printTimePeriods(start, end):
    start_month, start_year = start.split("-")
    end_month, end_year = end.split("-")
    # Cast year to int
    start_year, end_year = int(start_year), int(end_year)

    # For every year
    for year in range(start_year, end_year + 1):
        month_index = 12
        # Check if we are in the last year
        if year == end_year:
            month_index = months.index(end_month) + 1
        # For every month print the period
        for month in range(months.index(start_month), month_index):
            print months[month], year
        # New year
        start_month = "JAN"

printTimePeriods(start_period, end_period)

【讨论】:

    猜你喜欢
    • 2020-05-04
    • 1970-01-01
    • 1970-01-01
    • 2016-02-25
    • 1970-01-01
    • 2022-07-04
    相关资源
    最近更新 更多