2012-07-26 72 views
1

這裏有一些似乎有點愚蠢:datetime.strptime()很高興接受月份名稱的迭代列表,當我只是手工創建一個列表(months = ['January','February'])但不是當我遍歷由calendar.month_name創建月份列表,即使都返回<type 'str'>迭代的calendar.month_name不能被strptime解析()

斷碼:

import datetime 
import calendar 
for month in calendar.month_name: 
    print datetime.datetime.strptime(month,"%B") 

錯誤: ValueError: time data '' does not match format '%B'

工作代碼:

import datetime 
months = ['January','February','March'] 
for month in months: 
    print datetime.datetime.strptime(month,"%B") 

結果:

1900-01-01 00:00:00 
1900-02-01 00:00:00 
1900-03-01 00:00:00 

這是怎麼回事?這是python的for循環的行爲,我不熟悉?

回答

4

嘗試做print(list(calendar.month_name))爲什麼失敗會成爲明顯的很快......(主要是因爲第一個元素產生是一個空字符串)。需要注意的是第一個月產生的原因是一個空字符串,是因爲他們想month_names[1]對應January因爲是常見的約定(見documentation

可以做這樣的事情:

a = list(calendar.month_names)[1:] 

或者這也至少工作在CPython的(雖然目前尚不清楚在文檔中,如果它應該):

a = calendar.month_names[1:] 
+0

感謝您指出我在正確的方向!它看起來像循環開始的索引1('月份在calendar.month_name [1:]:')也適用。那很棒! – 2012-07-26 18:33:09

+0

@ wire42 - 是的,我也意識到這一點(經過一些實驗)。文檔使用術語'array',這對於返回類型有點含糊不清。但是,這似乎是可切片(至少在CPython的) – mgilson 2012-07-26 18:34:36

1

由於noted by mgilson中的第一項返回的是一個空字符串。這是微不足道的忽略它:

for month in calendar.month_name: 
    if month: 
     print datetime.datetime.strptime(month,"%B") 

或者用一個列表理解將其刪除:

for month in [month_name for month_name in calendar.month_name if month_name]: 
    print datetime.datetime.strptime(month,"%B") 
+0

Python的'if'的強大簡單(和'for')語句讓我高興和緊張在同一時間。它聽起來像是在說「如果這是一個月」,但當然「如果」不知道它是否是一個月。它只是在空字符串上返回false。不過,這是一個非常優雅的解決方案。你認爲它比基於分片的解決方案更強大嗎? – 2012-07-26 18:44:23

+0

@ wire42,這取決於你所說的「健壯」。它確實處理了新的空白字符串被添加到列表的某處或刪除的情況 - 但這不太可能發生。使用切片符號可能更好地表達了它是基於1的數組的事實。 – 2012-07-26 19:22:40