在Python中的迭代过程中更改范围的值 [英] Changing the value of range during iteration in Python

查看:79
本文介绍了在Python中的迭代过程中更改范围的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

>>> 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

这篇关于在Python中的迭代过程中更改范围的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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