如果我有这段代码
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 :(得分:3)
我可能误解了你在做什么,但似乎你想在第一次迭代时对s [:3]做一些事情,在第二次迭代时对s [3:6]有所不同,而在第三个是[6:]。换句话说,这根本不是一个循环!用一个接一个地写出这三个代码块,用s [:3]代替grp。
答案 1 :(得分: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
包含非重复代码,然后您必须将其移出“bar”(与“foo”一起应该给出更具描述性的名称)。
答案 2 :(得分: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]
。
答案 3 :(得分: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
方法则不会产生此类风险。
答案 4 :(得分: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']
,这应该仍然有用。