首页 > 解决方案 > 列出 python 元组,边缘情况

问题描述

我有一个点位置列表,作为元组,我试图收集点 N 之前和之后的点。

points = [
    (0, 0),
    (1, 1),
    (2, 2),
    (3, 3),
    (4, 4),
    (5, 5),
    (6, 6),
]

例如。如果我将第三点(3, 3)作为输入,则预期输出为[(2,2), (4,4)].

测试一下,它工作正常:

index = 3
a, n, b = points[ index-1 : index+2 ]
print(a, b)
# Returns: (2, 2) (4, 4)

只要索引不小于 2 或大于 5,它就可以按预期工作。

下面是一些元组列表按预期运行的示例:

# Tuple at index zero
print(points[0])
# Returns: (0, 0)
# Tuples from index zero to (but not including) index three
print(points[0:3])
# Returns: [(0, 0), (1, 1), (2, 2)]
# Tuple at index negative one, (6,6) in this case
print(points[-1])
# Returns: (6, 6)

但是,当我将负指数和正指数结合起来时,它会分崩离析,为什么?

# Tuples from index negative one, up to but not including index two
print(points[-1:2])
# Returns: []

预期的输出是[(6, 6), (0, 0), (1, 1)]Python 给出[]的 .

解决方案

感谢 Dev Khadka。

points = [
    (0,0),
    (1,1),
    (2,2),
    (3,3),
    (4,4),
    (5,5),
    (6,6),
]

index = 0
a, _, b = np.roll(points, -(index-1), axis=0)[:3]
sel_points = zip(a,b)
print(list(zip(*sel_points)))

Result: [(6, 6), (1, 1)]

标签: python

解决方案


points[-1:2]等效于points[-1:2:1]您尝试从最后一个元素开始索引并通过每次提前 1 步到达索引 2 的意思。如果您将步骤 -1 放置,此索引将起作用,points[-1:2:-1]但这不是您想要的。您可以使用下面的滚动方法来实现您想要的

points = [
    (0, 0),
    (1, 1),
    (2, 2),
    (3, 3),
    (4, 4),
    (5, 5),
    (6, 6),
]

indx = 3
a,_,b = np.roll(points, -(indx-1), axis=0)[:3]
a,b

推荐阅读