Changing the value of range during iteration in Python(在 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 中的迭代期间更改范围的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Python 中的迭代期间更改范围的值
基础教程推荐
- 尝试制作WhatsApp机器人 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
