当使用增量为3的for循环范围时,为什么第一个数字“group”会与它自己匹配?

2024-04-26 07:54:15 发布

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

我们在一节课上使用了以下书籍: craftbuzzcoder。 在第3部分(循环)中的墙和立方体一节中,他们面临创建倒金字塔的挑战。你知道吗

以下是本书的解决方案:

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轴/j变量)是由其自身而不是由3的增量来计数/分组的。你知道吗

为什么会这样?你知道吗

太长了,读不下去了,博士><强> > 我希望它会这样增长: enter image description here

相反,它似乎是这样的: enter image description here

为什么?你知道吗


Tags: ingameforpositionrange序列数字解决方案
2条回答

您需要了解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范围。你知道吗

在产生每个值之后,应用范围的step部分。range(0,10)中的第一件事是0,然后您添加3以获得3,然后6,等等。您没有选择组的大小,只是选择值每一步增加多少。你知道吗

相关问题 更多 >