所以我的问题是没有正确递增...我试图使用int" step"每次运行此循环时为+ 1,但它没有做任何事情。这是为什么?此外,当我打印(步骤)它只加起来337.它不像我想象的那样完整的1000。我该如何正确地做到这一点?
lockers = []
step = 3
locker = 0
while len(lockers) <= 1000:
lockers.append(1)
for i in range(0, len(lockers)):
lockers[i] = 0
for i in range(0, len(lockers), 2):
lockers[i] = 1
for i in range(0, len(lockers), step):
if lockers[i] == 0:
lockers [i] = 1
else:
lockers[i] = 0
step += 1
print(lockers)
答案 0 :(得分:0)
如果要在迭代时调整步长,可以拥有自己的范围对象:
class AdjustableRange(object):
def __init__(self, start, stop, step):
self.start = start
self.stop = stop
self.step = step
self.value = None
def __iter__(self):
if self.value is None:
self.value = start
while self.value < self.stop:
yield self.value
self.value += self.step
这个(未经测试的)可用于迭代的
rg = AdjustableRange(0, len(lockers), step):
for i in rg:
if lockers[i] == 0:
lockers [i] = 1
else:
lockers[i] = 0
rg.step += 1 # this influences the iteration
但是,正如已经说过的,有更好的方法来解决你的“真正的”问题。