【问题标题】:Skip 2 Index In the body of For Loop VS While Loop ( Python VS C++)跳过 For 循环 VS While 循环(Python VS C++)主体中的 2 索引
【发布时间】:2022-01-03 03:08:14
【问题描述】:

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

【问题讨论】:

    标签: python c++


    【解决方案1】:

    您可以使用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

    【讨论】:

    • 在这种情况下使用 Python 似乎更容易使用 while 循环,对吧?
    • 是的,这会更容易,但如果你特别想使用for,这是一个选项
    猜你喜欢
    • 2012-10-02
    • 1970-01-01
    • 2012-01-05
    • 2023-04-02
    • 1970-01-01
    • 2013-09-09
    • 1970-01-01
    • 2021-05-04
    • 2011-07-27
    相关资源
    最近更新 更多