跳过For循环VS While循环(Python VS C++)正文中的2个索引
Skip 2 Index In the body of For Loop VS While 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循环(第二个代码(来实现这一点?
第一个代码(用于循环(
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
相关文章:
- 如何循环打印顶点结构
- 如何在C++中从两个单独的for循环中添加两个数组
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 正在尝试了解输入验证循环
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 循环后如何继续阅读
- Ardunio UNO解决了多个重叠的定时器循环
- Eigen如何在容器循环中干净地附加矩阵
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- Cmake生成了VS项目的循环依赖关系,但没有制作文件.如何避免
- 使用基于自动的范围用于循环VS,使用对循环范围的基于对的范围
- C vs Java速度(带有算术的循环)
- C vs Java:无尽的循环创建对象仅崩溃C
- C++迭代器行为在 for vs while 循环中
- 'for' 循环中的 'int i = 0' vs. 'int i(0)'(赋值与初始化计数变量)
- 为什么具有多个嵌套循环的代码可以在 GCC 上立即完成,但在 VS 上需要很长时间
- 2个while循环vs if else语句在1个while循环中
- 无限循环vs boost::asio::deadline_timer c++性能
- For循环退出条件(size_t vs. int)