2014-07-24 72 views
0

因此,con只是一個條件,我匹配來自我建立的日期發生器。這個函數的所有輸出都是不可變的。所以我有將這些輸出轉換爲字符串的'超棒'任務。原因是我想附加/預先標記輸出。處理大量變量時,這會變得非常麻煩。確切的365天。Python列表效率:將變量批量轉換爲str和列表生成

con0 = str(context[0]) 
con1 = str(context[1]) 
con2 = str(context[2]) 
con3 = str(context[3]) 
con4 = str(context[4]) 
con5 = str(context[5]) 
con6 = str(context[6]) 
con7 = str(context[7]) 
con8 = str(context[8]) 
con9 = str(context[9]) 
con10 = str(context[10]) 
con11 = str(context[11]) 
con12 = str(context[12]) 
... 
con364 = str(context[364]) 

day0 = con0[0:10].replace("-", ""); 
day1 = con1[0:10].replace("-", ""); 
day2 = con2[0:10].replace("-", ""); 
day3 = con3[0:10].replace("-", ""); 
day4 = con4[0:10].replace("-", ""); 
day5 = con5[0:10].replace("-", ""); 
day6 = con6[0:10].replace("-", ""); 
day7 = con7[0:10].replace("-", ""); 
day8 = con8[0:10].replace("-", ""); 
day9 = con9[0:10].replace("-", ""); 
day10 = con10[0:10].replace("-", ""); 
day11 = con11[0:10].replace("-", ""); 
day12 = con12[0:10].replace("-", ""); 
... 
day364 = con364[0:10].replace("-", ""); 


exclude = [ ' "/' + year0 + "/" + day0 + "*" + '"', ' "/' + year0 + "/" + day1 + "*" + '"', ' "/' + year0 + "/" + day2 + "*" + '"', ' "/' + year0 + "/" + day3 + "*" + '"', ' "/' + year0 + "/" + day4 + "*" + '"', ' "/' + year0 + "/" + day5 + "*" + '"', ' "/' + year0 + "/" + day6 + "*" + '"', ' "/' + year0 + "/" + day7 + "*" + '"', ' "/' + year0 + "/" + day8 + "*" + '"', ' "/' + year0 + "/" + day9 + "*" + '"', ' "/' + year0 + "/" + day10 + "*" + '"', ' "/' + year0 + "/" + day11 + "*" + '"', ' "/' + year0 + "/" + day12 ... + year0 + "/" + day364 + "*" + '"' ] 

d0 = ' "*%s*"\n' % (day0) 
y0 = ' "/%s/*"\n' % (year0) 
w0 = ' %s\n'' %s\n'' %s\n'' %s\n'' %s\n'' %s\n'' %s\n'' %s\n'' %s\n'' %s\n'' %s\n'' %s\n'' %s\n' % (exclude[7],exclude[8],exclude[9],exclude[10],exclude[11],exclude[12]....exclude[364]) 

有沒有進行批量字符串替換和生成列表比使用我的for i慶典更容易更Python的方式循環,以建立他們給我嗎?

回答

1

當你有許多變量都以數字結尾時,這是一個很好的跡象,你應該使用單個列表來代替。您可以使用列表推導簡潔地構造一個列表。

cons = [str(context[i]) for i in range(365)] 
days = [con[0:10].replace("-", "") for con in cons] 
exclude = [' "/{}/{}*"'.format(year0, day) for day in days] 
w0 = "\n".join(" " + day for for day in days) 
+0

呵呵。感謝您的意見。 – shdobxr