假设我有一个度值数组,如下所示:
DEGREES = [
0, 15, 30, 45, 60,
75, 90, 105, 120,
135, 150, 165, 180,
195, 210, 225, 240,
255, 270, 285, 300,
315, 330, 345,
]
我会选择一个角度,然后将这个假设的圆平分,以便更容易找到到达目标方向的最短路线。在
既然如此,我怎样才能选择一个特定的值,比如90
,然后能够找到后面的12个元素,包括结尾的索引?在
所以,取前面的值,应用到这个列表中,我会得到这样的结果:
^{pr2}$使用切片表示法,我尝试这样做:
index = DEGREES.index(90)
print(DEGREES[index-12:index]) # start 12 values back, stop at index
但这只打印一个空数组。在
有没有一种方法可以对列表进行切片,这样我就可以在我使用的索引后面得到前面的12个值?在
编辑:
这是一个XY问题,我的错。最初,我试图在Pygame中创建一个平滑的旋转系统,由于我试图计算角度的尝试不起作用,我提出这个问题是为了用我正在尝试实现的另一个想法来解决一个问题。我最终接受了帮助我建立平稳旋转系统的答案,但下面有与原始问题相关的答案。在
有角算术
你的目标不是分割、连接或反转列表。你的目标是用度数做基本的算术,并将结果保持在}之间。为此,您应该使用modulo运算符^{} :
0
和{回到问题上来
如果您只想对具有恒定增量的度数使用此切片,则可以直接生成所需的列表:
^{pr2}$你真正的问题
你在评论中写道:
从两个角度,你需要决定是顺时针还是逆时针旋转。您可以再次使用模来确保旋转在-180°和179°之间:
下面是一个例子:
现在可以创建一个角度列表,以最短的方向旋转:
例如:
如果
increment
不是整数,则列表使用float以避免丢失end_angle
。在这样的话可能更直接:
或者您可以使用^{} :
你可以用它作为函数:
^{pr2}$相关问题 更多 >
编程相关推荐