跳过For循环VS While循环(Python VS C++)正文中的2个索引

Skip 2 Index In the body of For Loop VS While Loop ( Python VS C++)

本文关键字:循环 VS 正文 2个 索引 Python For While 跳过 C++      更新时间:2024-05-10

在下面的第一段代码(使用for循环(中,当我想通过增加for循环正文中的索引来跳过2个索引时,它会忽略i = i+2,只使用for i in range (len(c))短语更新索引,而在c++中,我们可以通过for (int i = 0 ; i <sizeof(c) ;i++){i += 2;}在for循环的正文中这样做。有没有使用for循环(通过更正第一个代码(或我必须使用while循环(第二个代码(来实现这一点?

第一个代码(用于循环(

def jumpingOnClouds(c):
count_jumps = 0 

for i in range (len(c)):       
if (i+2 <len(c) and c[i] == 0 and c[i+2] ==0):
i = i+2
count_jumps+=1#It doesnt let me to update i in the while loop

elif (i+1 <len(c) and c[i] == 0 and c[i+1] ==0):

count_jumps+=1

else:
pass    

return(count_jumps)

c = [0, 0, 0, 1, 0, 0]

jumpingOnClouds(c)

第二个代码(While Loop(

def jumpingOnClouds(c):
count_jumps = 0 

i = 0

while( i < len(c)):       
if (i+2 <len(c) and c[i] == 0 and c[i+2] ==0):
i = i+2
count_jumps+=1

elif (i+1 <len(c) and c[i] == 0 and c[i+1] ==0):

count_jumps+=1
i = i+1

else:
i = i+1   

return(count_jumps)
c = [0, 0, 0, 1, 0, 0]

jumpingOnClouds(c)

您可以使用continue跳过。您只需要一个条件,即True

def jumpingOnClouds(c):
skipCondition = False
count_jumps = 0 

for i in range (len(c)):       
if skipCondition:
skipCondition = False
continue
if (i+2 <len(c) and c[i] == 0 and c[i+2] ==0):
count_jumps+=1#It doesnt let me to update i in the while loop
skipCondition = True
continue

elif (i+1 <len(c) and c[i] == 0 and c[i+1] ==0):

count_jumps+=1

else:
pass    

return(count_jumps)

c = [0, 0, 0, 1, 0, 0]

jumpingOnClouds(c)

放置continue将继续迭代,但在此之前,它将生成skipCondition = True。下一次迭代,skipCondition将是True,所以您将再次跳过,但将skipCondition设置回False