列出python元组,边缘情况

时间:2019-10-19 17:24:30

标签: 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)]

1 个答案:

答案 0 :(得分:0)

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