在Python中,基于索引及其后面的项对列表进行切片

2024-09-27 22:23:15 发布

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

假设我有一个度值数组,如下所示:

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中创建一个平滑的旋转系统,由于我试图计算角度的尝试不起作用,我提出这个问题是为了用我正在尝试实现的另一个想法来解决一个问题。我最终接受了帮助我建立平稳旋转系统的答案,但下面有与原始问题相关的答案。在


Tags: 答案元素目标列表index系统切片数组
3条回答

有角算术

你的目标不是分割、连接或反转列表。你的目标是用度数做基本的算术,并将结果保持在0和{}之间。为此,您应该使用modulo运算符^{}

>>> 90 % 360
90
>>> 390 % 360
30
>>> -60 % 360
300
>>> 360 % 360
0

回到问题上来

如果您只想对具有恒定增量的度数使用此切片,则可以直接生成所需的列表:

^{pr2}$

你真正的问题

你在评论中写道:

This array of degrees is designed to work with a smooth rotation system that I'm trying to create in pygame. Normally I would just find the difference between the current direction and the target direction and increment from there, but since the rotation rolls over at zero I have to hardcode the values to make sure that it will always go the shortest route possible.

从两个角度,你需要决定是顺时针还是逆时针旋转。您可以再次使用模来确保旋转在-180°和179°之间:

def shortest_rotation(start_angle, end_angle):
    return (end_angle - start_angle + 180) % 360 - 180

下面是一个例子:

>>> shortest_rotation(0, 90)
90
>>> shortest_rotation(90, 0)
-90
>>> shortest_rotation(90, 90)
0
>>> shortest_rotation(90, 330)
-120
>>> shortest_rotation(0, 180)
-180
>>> shortest_rotation(0, 181)
-179
>>> shortest_rotation(0, 179)
179
>>> shortest_rotation(10, 350)
-20

现在可以创建一个角度列表,以最短的方向旋转:

def rotation_steps(start_angle, end_angle, n):
    increment = shortest_rotation(start_angle, end_angle) / n
    return [(start_angle + i * increment) % 360 for i in range(n + 1)]

例如:

>>> rotation_steps(90, 270, 12)
[90.0, 75.0, 60.0, 45.0, 30.0, 15.0, 0.0, 345.0, 330.0, 315.0, 300.0, 285.0, 270.0]
>>> rotation_steps(10, 350, 2)
[10.0, 0.0, 350.0]

如果increment不是整数,则列表使用float以避免丢失end_angle。在

这样的话可能更直接:

index = DEGREES.index(90)
print([DEGREES[i] for i in range(index, index-13, -1)])

或者您可以使用^{}

from collections import deque
from itertools import islice

dq = deque(reversed((0, 15, 30, 45, 60,
    75, 90, 105, 120,
    135, 150, 165, 180,
    195, 210, 225, 240,
    255, 270, 285, 300,
    315, 330, 345)))

index = dq.index(90)
dq.rotate(-index)
res = list(islice(dq, 13))
# [90, 75, 60, 45, 30, 15, 0, 345, 330, 315, 300, 285, 270]

你可以用它作为函数:

^{pr2}$

相关问题 更多 >

    热门问题