如果你想让事情变得过于复杂,你可以创建一个定制的生成器,在那里你可以使用
generator.send
方法在迭代过程中传递新的步骤。
def variable_step_generator(start, stop=None, step=1):
if stop is None:
start, stop = 0, start
while start < stop:
test_step = yield start
if test_step is not None:
step = test_step
yield
start += step
用法如下:
variable_step_range = variable_step_generator(1, 100)
for i in variable_step_range:
print i
if i == 10:
variable_step_range.send(10)
if i == 90:
variable_step_range.send(1)
# 1, 2, 3, 4, 5, 6, 7, 8, 9,
# 10, 20, 30, 40, 50, 60, 70, 80, 90,
# 91, 92, 93, 94, 95, 96, 97, 98, 99
但这其实只是一个包装纸
while
循环其他答案的建议。