python - for 循环中递增

标签 python

所以我的问题是这个没有正确递增...我尝试在每次运行此循环时使用 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)

最佳答案

range 为您提供一个可迭代对象:

>>> 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:

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

要获得类似于 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

然后您可以执行 for i in advance_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):

使用 bool 值代替 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。

关于python - for 循环中递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33050384/

相关文章:

python - 字段名称选择 'reference' 不是有效选择问题

python - 在 Pandas 中减少(折叠)

python - 如何使用 pandas 将在线 csv 文件保存到计算机

python - 在 Pandas 中执行类似 excel 的计数

python - 为什么这个实例成员在 Python 中实例化后无法访问?

python - 如何将 Postgres 结果集作为 CSV 从远程数据库连接导出到本地机器?

python - 为什么我不能在范围函数上使用关键字参数?

python - 继承中命名空间的顺序是什么?

python - range() 函数没有产生预期的结果

python - 如果数字之间没有出现句点 [.] 和逗号 [,],则从字符串中删除它们