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


- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01