有没有办法更有效地编写这个循环?

时间:2015-02-18 08:42:20

标签: python loops while-loop

i = 2
while (i != len(recipe)):
        print(recipe[i])
        i += 1
        print(recipe[i])
        i += 1
        print(recipe[i])
        i += 1

这个while循环可以写得更简单,它看起来很麻烦

2 个答案:

答案 0 :(得分:1)

类似的东西:

for item in recipe[2:]:
   print(item)

虽然在原始代码抛出IndexError的情况下,行为不会完全相同。

答案 1 :(得分:1)

i = 2
length = len(recipe)
while(i != length):
    print(recipe[i])
    print(recipe[i+1])
    print(recipe[i+2])
    i += 3

i = 2
length = len(recipe)
while(i != length):
    print(recipe[i],recipe[i+1],recipe[i+2])
    i += 3

显然你必须处理IndexError