繁体   English   中英

Skip 2 Index 在for循环体中,Python VS C++

[英]Skip 2 Index In the body of for loop, Python VS C++

在下面的第一个代码中(使用 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循环(第二个代码)?

第一个代码(For循环)

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 循环)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM