<p><code>range</code>给您一个iterable对象:</p>
<pre><code>>>> range(10,20 , 2)
range(10, 20, 2)
>>> list(range(10,20 , 2))
[10, 12, 14, 16, 18]
</code></pre>
<p>它中的值在调用返回时就完全确定,并且不会在循环中每次都重新计算。您的<code>step</code>只增加到337,因为您要为对象<code>range(0, 1000, 3)</code>中的每个元素增加一次,该对象有334项,而不是1000:</p>
^{pr2}$
<p>要获得类似<code>range</code>但推进<code>step</code>的东西,您需要编写自己的生成器:</p>
^{3}$
<p>然后您可以执行<code>for i in advancing_range(0, 1000, 3):</code>,它将按您的意愿工作。在</p>
<p>但这是一件很奇怪的事。从你的变量名来看,我猜你在编码<a href="http://mathforum.org/library/drmath/view/54242.html" rel="nofollow">locker problem</a>,它说:</p>
<blockquote>
<p>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?</p>
</blockquote>
<p>但是前进距离逻辑说的更像“第一个学生打开第一个储物柜,然后第二个学生打开第二个储物柜,然后第三个学生在那之后打开第三个储物柜……”。您希望每次都影响多个储物柜,但间隔更远。本质上,您希望将前两个循环再复制和粘贴998次,每次都使用一个更高的<code>step</code>。当然,您可以比复制和粘贴做得更好,这似乎需要两个嵌套循环,其中外部循环推进内部循环使用的<code>step</code>。应该是这样的:</p>
<pre><code>for step in range(1, len(lockers)):
for i in range(step, len(lockers), step):
</code></pre>
<p>通过使用布尔值而不是<code>1</code>和<code>0</code>来简化其他逻辑,整个程序如下所示:</p>
<pre><code>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))
</code></pre>
<p>上面显示打开的储物柜是969个。在</p>