Python for循环递减索引 [英] Python for loop decrementing index

查看:46
本文介绍了Python for循环递减索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我写了一个这样的 for 循环:

So I wrote a for loop like this:

for i in range(size):
  if(.....)
    ....
    i-=1
  else:
    ....

如果它在 if 语句中,我尝试将索引减少 1,但显然我不能这样做.有没有其他方法可以减少 for 循环中的 i ?

I try to decrease the index by 1 if it is inside the if statement, but apparently I can't do that. Is there any other way that I can decrease i in a for loop?

推荐答案

我想通过此处提供的文档再次讨论 range() 函数:Python 3.4.1 range(start, stop[, step]) 文档

I would like to go over the range() function yet again through the documentation as provided here: Python 3.4.1 Documentation for range(start, stop[, step])

如上面的文档所示,你可以为范围函数'start'、'stop'和'step'输入三个参数,最后它会给你一个不可变序列.

As shown in the documentation above, you may enter three parameters for the range function 'start', 'stop', and 'step', and in the end it will give you an immutable sequence.

'start' 参数定义了你的案例 'i' 的计数器变量应该从什么时候开始.'end' 参数本质上是 size 参数在您的情况下所做的.至于您想要什么,因为您希望每次循环将变量i"减少 1,您可以将参数step"设为 -1,这表示在 for 循环的每次迭代中,变量i"将下降 1.

The 'start' parameter defines when the counter variable for your case 'i' should begin at. The 'end' parameter is essentially what the size parameter does in your case. And as for what you want, being that you wish to decrease the variable 'i' by 1 every loop, you can have the parameter 'step' be -1 which signifies that on each iteration of the for loop, the variable 'i' will go down by 1.

您也可以将 'step' 设置为 -2 或 -4,这将使 for 循环在每次递增 2 或 4 时分别向下计数 'i'.

You can set the 'step' to be -2 or -4 as well, which would make the for loop count 'i' down on every increment 2 down or 4 down respectively.

示例:

for x in range(9, 3, -3):
    print(x)

打印输出:9, 6.它从 9 开始,在 3 结束,然后递减计数器 3.当它达到 3 时,它会停止,因此为什么不打印 '3' 本身.

Prints out: 9, 6. It starts at 9, ends at 3, and steps down by a counter of 3. By the time it reaches 3, it will stop and hence why '3' itself is not printed.

刚刚注意到您可能想要减少 for 循环中的i"值...?然后我会做的只是有一个 while 循环,而不是在那里你可以公开一个变量,你可以随心所欲地修改.

Just noticed the fact that it appears you may want to decrease the 'i' value in the for loop...? What I would do for that then is simply have a while loop instead where you would have a variable exposed that you can modify at your whim.

test = 0
size = 50
while (test < size)
    test += 1
    if (some condition):
        test -= 1

这篇关于Python for循环递减索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆