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 中的迭代期间更改范围的值
基础教程推荐
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 求两个直方图的卷积 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 包装空间模型 2022-01-01
