简体   繁体   English

在 for 循环中递增

[英]Incrementing in a for loop

So my issue is with this not incrementing correctly... I tried to uses an int "step" to + 1 every time this loop is ran but it doesn't do anything.所以我的问题是这个没有正确递增......每次运行这个循环时,我试图使用一个 int“step”到 + 1 但它没有做任何事情。 Why is that?这是为什么? Also when I print(step) it only adds up to 337. It does not go the full 1000 like I had thought I asked it too.此外,当我打印(步骤)时,它的加起来只有 337。它并没有像我想的那样达到 1000。 How do I do this correctly?我该如何正确地做到这一点?

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)

range gives you an iterable object: range给你一个可迭代的对象:

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

The values in it are fully decided as soon as the call returns, and aren't re-evaluated each time around the loop.一旦调用返回,其中的值就会完全确定,并且不会在每次循环时重新评估。 Your step only goes up to 337 because you are incrementing it once for each element in the object range(0, 1000, 3) , which has 334 items, not 1000:您的step只会增加到 337,因为您要为对象range(0, 1000, 3)中的每个元素增加一次,它有 334 个项目,而不是 1000:

>>> len(range(0,1000,3))
334

To get something that works like range but advances the step , you would need to write your own generator:要获得类似range但前进step ,您需要编写自己的生成器:

def advancing_range(start, stop, step):
    ''' Like range(start, stop, step) except that step is incremented 
        between each value 
    '''
    while start < stop:
        yield start
        start += step
        step += 1

You can then do for i in advancing_range(0, 1000, 3): and it will work as you intend.然后for i in advancing_range(0, 1000, 3):您可以for i in advancing_range(0, 1000, 3):执行操作for i in advancing_range(0, 1000, 3):它将按您的预期工作。

But this is a very strange thing to want to do.但这是一件很奇怪的事情。 Judging by your variable names, I would guess you're coding the locker problem , which says:从你的变量名来看,我猜你正在编写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.学校有1000个储物柜,编号从1到1000。 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.第三个学生将更改所有 3 的倍数的储物柜门(更改意味着关闭打开的储物柜,打开关闭的储物柜。)第四个学生将更改所有编号为 4 的倍数的储物柜门的位置,依此类推在。 After 1,000 students have entered the school, which locker doors will be open, and why? 1000名学生进入学校后,哪些更衣室门会打开,为什么?

But the advancing range logic says something more like "the first student opens the first locker, then the second opens the second locker after that, then the third student opens the third locker after that ...".但是前进范围逻辑更像是“第一个学生打开第一个储物柜,然后第二个打开第二个储物柜,然后第三个学生打开第三个储物柜......”。 You want to affect multiple lockers each time, but further spaced out.你想每次影响多个储物柜,但间隔更远。 Essentially, you want to copy and paste your first two loops another 998 times with a one higher step each time.本质上,您希望将前两个循环再复制和粘贴 998 次,每次都提高一个step Of course, you can do better than copy and paste, and this seems like you want two nested loops, where the outer one advances the step that the inner one uses.当然,您可以比复制和粘贴做得更好,这似乎需要两个嵌套循环,其中外部循环推进内部循环使用的step That would look like this:那看起来像这样:

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

Simplifying your other logic by using booleans instead of 1 and 0 , the whole program looks like this:通过使用布尔值而不是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))

It prints that the number of open lockers is 969.它打印出打开的储物柜数量是 969。

If you want to adjust the step size while iterating, you can have an own range object:如果你想在迭代时调整步长,你可以有一个自己的 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

This (untested) one you can use for iterting like这个(未经测试的)一个你可以用来迭代的

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

But, as was already said, there are better ways to solve your "real" problem.但是,正如已经说过的,有更好的方法来解决您的“真实”问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM