2013-02-24 213 views
0

我正在寫應該以列表的列表這樣工作,如果我用這個例子:變量命名爲循環

def mode(year): 
    monthAmount = len(year) 

    for month in year: 
     (month)Index = len(month) 

我想這是什麼做的是,說是[1月,2月,3月],結果應該是這樣的:JanuaryIndex = *,FebruaryIndex = *,MarchIndex = *等等;有幾個不同的月份。是否有捷徑可尋?謝謝。

回答

3

我不完全確定你在這裏尋找什麼。

爲了得到一個索引的順序你遍歷與實際值在一起,使用enumerate() function

for index, month in enumerate(year): 
    print index, month 

你真的不想要動態設置全局變量。使用字典來代替:

monthindices = {} 

for month in year: 
    monthindices[month] = len(month) 

可以動態創建全局變量,通過訪問globals() mapping,但這樣做是一般一個壞主意。如果你很頑固,你會這樣做:

gl = globals() 
for month in year: 
    gl['{}Index'.format(month)] = len(month)