2010-03-02 77 views
0

如果我有這樣的代碼更好循環,字符串處理(蟒)

s = 'abcdefghi' 
for grp in (s[:3],s[3:6],s[6:]): 
    print "'%s'"%(grp) 

    total = calc_total(grp) 

    if (grp==s[:3]): 
     # more code than this 
     p = total + random_value 
     x1 = my_function(p) 

    if (grp==s[3:6]): 
     # more code than this 
     p = total + x1 
     x2 = my_function(p) 

    if (grp==s[6:]): 
     # more code than this 
     p = total + x2 
     x3 = my_function(p) 

如果組是第一組,該組執行代碼,如果該組是第二組,使用所述執行代碼從第一組執行的代碼生成的值,對於第三組使用從第二組代碼生成的值生成的值相同:

如何整理這些以使用更好的循環?

感謝

回答

0

如下我的代碼是這樣的:

for i, grp in enumerate((s[:3],s[3:6],s[6:])): 
    print "'%s'"%(grp) 

    total = calc_total(grp) 
    # more code that needs to happen every time 

    if i == 0: 
     # code that needs to happen only the first time 
    elif i == 1: 
     # code that needs to happen only the second time 

==檢查可能會產生誤導,如果其中一組「恰好」是同一個又一個,而enumerate方法沒有這種風險。

3

我可能誤會你在做什麼,但似乎你想要做的事,以S [3]在第一次循環,不同的東西S [3:6]上第二,還有其他的東西在第三個[6:]。換句話說,那根本不是一個循環!只需將這三個代碼塊一個接一個地寫出來,用s [:3]等代替grp。

+0

對不起,我忘了包含我的'total = calc_total(grp)'語句 – joec 2010-03-02 18:30:54

0
x = reduce(lambda x, grp: my_function(calc_total(list(grp)) + x), 
     map(None, *[iter(s)] * 3), random_value) 

最後,你會有最後的x

或者,如果你想保持周圍的中間結果,

x = [] 
for grp in map(None, *[iter(s)] * 3): 
    x.append(my_function(calc_total(list(grp)) + (x or [random_value])[-1])) 

然後你有x[0]x[1]x[2]

0

讓您的數據轉換成你想要的清單,然後嘗試以下方法:

output = 0 
seed = get_random_number() 
for group in input_list: 
    total = get_total(group) 
    p = total + seed 
    seed = my_function(p) 

input_list需要像['abc', 'def', 'ghi']。但是如果你想把它擴展到['abc','def','ghi','jkl','mno','pqr'],這應該仍然有效。

1

我必須說我同意彼得,因爲循環是多餘的。如果你是怕複製代碼,然後只要將重複的代碼放到一個函數,並調用它多次:

s = 'abcdefghi' 

def foo(grp): 
    # Anything more you would like to happen over and over again 
    print "'%s'"%(grp) 
    return calc_total(grp) 

def bar(grp, value): 
    total = foo(grp) 
    # more code than this 
    return my_function(total + value) 

x1 = bar(s[:3], random_value) 
x2 = bar(s[3:6], x1) 
x3 = bar(s[6:], x2) 

如果

# more code than this 

包含非重複的代碼,那麼你必須,當然招從「酒吧」(與「富」一起應該給一個更具描述性的名字)。