2016-02-11 66 views
2

我給出了start_year,end_year,start_month和end_month例如Python:在兩個日期之間生成YYMM字符串

start_year = 2005 
end_year = 2017 
start_month = 3 
end_month = 2 

我想生成以下字符串: 0503.mat,0504.mat,0505.mat,0506.mat,0507.mat,0508.mat,0509.mat,0510.mat,0511。 0512.mat,0601.mat,。0612.mat,.....,... 1701.mat,1702.mat

即結合年份和月份並生成所有月份之間的這種組合給定的開始年/月和結束年/月

編輯:

.MAT正在重複上的所有輸出

這是我到目前爲止已經試過:

k = 0 
for yr in range(2005, 2007 + 1): 
    for mn in range(1, 12 + 1): 
     YYMM[k] = "{:02}{:02}.mat".format(yr % 100, mn)) 
     k = k + 1 

但顯然它不會覆蓋所有個月,如果我在3個月在2005年年內開工,並於2006年

+0

'.mat'是重複所有輸出? –

+0

是.mat正在重複所有輸出 – Zanam

+0

好吧...那麼你到底嘗試了什麼? –

回答

1

很簡單:

start_year = 2005 
end_year = 2007 
start_month = 3 
end_month = 2 
yymm = [(yy, mm) for yy in range(start_year, end_year + 1) for mm in range(1, 13) 
     if (start_year, start_month) <= (yy, mm) <= (end_year, end_month)] 

這將生成的元組

[(2005, 3), (2005, 4), (2005, 5), (2005, 6), (2005, 7), (2005, 8), 
(2005, 9), (2005, 10), (2005, 11), (2005, 12), (2006, 1), (2006, 2), 
(2006, 3), (2006, 4), (2006, 5), (2006, 6), (2006, 7), (2006, 8), 
(2006, 9), (2006, 10), (2006, 11), (2006, 12), (2007, 1), (2007, 2)] 

我會離開的字符串格式化你的列表。

工作原理:我們利用Python的元組比較機制。當比較(x1, x2, ... xn)(y1, y2, ... yn)時,如果它們不相等,那麼排序由x1y1確定,如果它們不相等,則通過x2y2確定排序,等等。

編輯: 要生成的字符串,您要使用列表比較,以及:速度更快,而且經常打掃得比for循環:

formatted_yymm = ['{:>02}{:>02}.mat'.format(yy % 100, mm) for yy, mm in yymm] 

結果:

['0503.mat', '0504.mat', '0505.mat', '0506.mat', '0507.mat', '0508.mat', 
'0509.mat', '0510.mat', '0511.mat', '0512.mat', '0601.mat', '0602.mat', 
'0603.mat', '0604.mat', '0605.mat', '0606.mat', '0607.mat', '0608.mat', 
'0609.mat', '0610.mat', '0611.mat', '0612.mat', '0701.mat', '0702.mat'] 
+0

您是否介意在此處發佈用於組合字符串的代碼,因爲我正在考慮編寫for循環來組合元素的元素。 – Zanam

+0

@ user1243255請參閱編輯。 – gil

+0

謝謝你永遠不會猜到你創建的字符串操作代碼。 – Zanam

-2
strings = ["{}{}.mat".format(str(year - 2000).zfill(2), str(month).zfill(2)) \ 
      for year in range(start_year, end_year + 1) \ 
      for month in range(start_month, end_month + 1)] 
繼續到第7個月
+0

對不起,我不清楚我的問題。上述解決方案中的月份並不涵蓋所有月份。 – Zanam

+0

個月的範圍是從1-12個週期 –

0

這可以變得更快,而且可能更易讀,而是讓數學做的工作:

>>> start = (start_year - 2000) * 12 + start_month 
>>> end = (end_year - 2000) * 12 + end_month 
>>> ["{:02d}{:02d}.mat".format(x // 12, x % 12) for x in range(start, end+1)] 

簡稱歐tput的

['0503.mat', '0504.mat', '0505.mat', '0506.mat', ... 
'1610.mat', '1611.mat', '1700.mat', '1701.mat', '1702.mat'] 
相關問題