当使用增量为 3 的 for 循环范围时,为什么第一个数字 'group' 到它自己?

When using a for loop range with an increment of three, why does the first number 'group' to itself?

我们正在 class 我正在做的助教中使用以下书籍: craftbuzzcoder。 在第 3 部分(循环) 部分 Wall & cube 中,他们面临着创建倒金字塔的挑战。

以下为书上解答:

for j in range(0,10,3): 
    for i in range (-j, j+1, 3):
        for k in range(-j, j+1, 3):
            game.set_block(Position(i, j+1, k), 45)

据我所知,似乎是相应范围序列中的第一个数字(例如,y-axis/j 变量)是 counted/grouped 本身而不是增量 3。

这是为什么?

tl;博士 我希望它像这样增加:

相反,它似乎是这样递增的:

为什么?

范围的 step 部分被应用 每个值产生之后。 range(0,10) 中的第一件事是 0,然后添加 3 得到 3,然后是 6,等等。您没有选择组的大小-- 每一步增加多少价值。

您需要了解 python 范围的工作原理,这对您来说会变得更容易。

range(start, stop[, step])

start is from where you want to start the iteration

stop is at where you want to stop the iteration, exclusive

step means how much you want to add to start

but there is a small catch with this, if step is positive, the last element is the largest start + i * step less than stop; if step is negative, the last element is the smallest start + i * step greater than stop. step must not be zero and step defaults to 1

所以在你的情况下它的工作方式是 -

for j in range(0,10,3):
    print j

我们得到 -

j = 0 -> add 3, j becomes 3 -> add 3, j becomes 6 -> add 3, j becomes 9, add 3, j becomes 12  which is greater than stop -> exit

更多 examples 范围。