2017-05-26 80 views
0

假設我的句點是NOV-2016MAR-2018,我需要打印所有句號,如(NOV-2016, DEC-2016, JAN-2017直到MAR-2018)。可以做些什麼來獲得理想的結果。現在我這樣做,但我沒有得到期望的結果:在Python中的兩個句點之間打印所有句號

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 
+0

什麼是你所得到的結果呢? – litelite

+0

NOV DEC JAN FEB MAR APR MAY JUN – saurav

+0

但我也應該從JUL再弄輸出回到JUN爲2018年和2019 – saurav

回答

0

我認爲這是比較容易,如果你每年迭代來處理你的問題。在每年年底將月份重置爲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)