在运行时更改 Python for 循环范围(上限)
Posted
技术标签:
【中文标题】在运行时更改 Python for 循环范围(上限)【英文标题】:Change Python for loop range (higher limit) at runtime 【发布时间】:2016-01-05 04:53:40 【问题描述】:如何在运行时更改 python for 循环的上限?
代码,
from random import randint
lower_limit = 0
higher_limit = 200
step_size = 5
for i in range(lower_limit, higher_limit, step_size):
# do something
higher_limit = higher_limit + randint(0, 5)
代码一直运行到第一个上限并且不关心声明的上限,可以做些什么来使它工作?
【问题讨论】:
【参考方案1】:也许您可以定义自己的范围版本(简化版):
from random import randint
def higher_range(start, upto, step, inc):
i = start
while i < upto:
yield i
i += step
upto += randint(0, inc)
for j in higher_range(0, 10, 5, 5):
print j
显然,不能保证它会很快终止......
【讨论】:
【参考方案2】:范围一经创建就无法修改。我认为重组逻辑并将range
替换为while
会更容易:
lower_limit = 0
higher_limit = 200
step_size = 5
i = 0
while lower_limit <= i < higher_limit:
# do something
i = i + step_size
higher_limit = higher_limit + randint(0, 5)
【讨论】:
【参考方案3】:你需要使用while:
from random import randint
lower_limit = 0
higher_limit = 200
step_size = 5
while i <higher_limit:
# do something
higher_limit = higher_limit + randint(0, 5)
i += 5
【讨论】:
谢谢,我没注意到。我改变了它:)以上是关于在运行时更改 Python for 循环范围(上限)的主要内容,如果未能解决你的问题,请参考以下文章