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 中的迭代期间更改范围的值


基础教程推荐
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 筛选NumPy数组 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01