2010-03-02 78 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 

包含非重复的代码,那么你必须,当然招从“酒吧”(与“富”一起应该给一个更具描述性的名字)。