在 Python 中的迭代期间更改范围的值

2022-01-24 00:00:00 python python-2.7 loops iteration range

问题描述

>>> k = 8
>>> for i in range(k):
        print i
        k -= 3
        print k

如果我在 for 循环中只使用 print i,上面是从 0-7 打印数字的代码.

Above the is the code which prints numbers from 0-7 if I use just print i in the for loop.

我想了解上面的代码是如何工作的,有什么方法可以更新 range(variable) 中使用的变量的值,使其迭代不同.

I want to understand the above code how it is working, and is there any way we can update the value of variable used in range(variable) so it iterates differently.

还有为什么它总是迭代到初始 k 值,为什么该值没有更新.

Also why it always iterates up to the initial k value, why the value doesn't updated.

我知道这是一个愚蠢的问题,但欢迎所有想法和评论.

I know it's a silly question, but all ideas and comments are welcome.


解决方案

范围生成后无法更改.在 Python 2 中,range(k) 将创建一个从 0 到 k 的整数列表,如下所示:[0, 1, 2, 3, 4, 5, 6, 7].在创建列表后更改 k 将无济于事.

You can't change the range after it's been generated. In Python 2, range(k) will make a list of integers from 0 to k, like this: [0, 1, 2, 3, 4, 5, 6, 7]. Changing k after the list has been made will do nothing.

如果要更改要迭代的数字,可以使用 while 循环,如下所示:

If you want to change the number to iterate to, you could use a while loop, like this:

k = 8
i = 0
while i < k:
    print i
    k -= 3
    i += 1

相关文章