在for循环中递增

2024-05-23 19:44:49 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我的问题是这个不能正确递增。。。每次运行这个循环时,我都尝试使用int“step”to+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)

Tags: toinforlenifstep步骤range
2条回答

range给您一个iterable对象:

>>> range(10,20 , 2)
range(10, 20, 2)
>>> list(range(10,20 , 2))
[10, 12, 14, 16, 18]

它中的值在调用返回时就完全确定,并且不会在循环中每次都重新计算。您的step只增加到337,因为您要为对象range(0, 1000, 3)中的每个元素增加一次,该对象有334项,而不是1000:

^{pr2}$

要获得类似range但推进step的东西,您需要编写自己的生成器:

^{3}$

然后您可以执行for i in advancing_range(0, 1000, 3):,它将按您的意愿工作。在

但这是一件很奇怪的事。从你的变量名来看,我猜你在编码locker problem,它说:

A new high school has just been completed. There are 1,000 lockers in the school and they have been numbered from 1 through 1,000. During recess (remember this is a fictional problem), the students decide to try an experiment. When recess is over each student will walk into the school one at a time. The first student will open all of the locker doors. The second student will close all of the locker doors with even numbers. The third student will change all of the locker doors that are multiples of 3 (change means closing lockers that are open, and opening lockers that are closed.) The fourth student will change the position of all locker doors numbered with multiples of four and so on. After 1,000 students have entered the school, which locker doors will be open, and why?

但是前进距离逻辑说的更像“第一个学生打开第一个储物柜,然后第二个学生打开第二个储物柜,然后第三个学生在那之后打开第三个储物柜……”。您希望每次都影响多个储物柜,但间隔更远。本质上,您希望将前两个循环再复制和粘贴998次,每次都使用一个更高的step。当然,您可以比复制和粘贴做得更好,这似乎需要两个嵌套循环,其中外部循环推进内部循环使用的step。应该是这样的:

for step in range(1, len(lockers)):
    for i in range(step, len(lockers), step):

通过使用布尔值而不是10来简化其他逻辑,整个程序如下所示:

lockers = [True] * 1000

for step in range(1, len(lockers)):
    for i in range(step, len(lockers), step):
        lockers[i] = not lockers[i]

print(sum(lockers))

上面显示打开的储物柜是969个。在

如果要在迭代时调整步长,可以有自己的range对象:

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

这个(未经测试)你可以用它来编写

^{pr2}$

但是,正如已经说过的,有更好的方法来解决你的“真正”问题。在

相关问题 更多 >