【发布时间】:2019-10-19 17:24:30
【问题描述】:
我有一个点位置列表,作为元组,我正在尝试收集点 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)]
【问题讨论】:
-
您好 Elias,您在理解符号时是否有问题,或者您只是在寻找解决方案?很少有其他帖子可以解释这种表示法。在我看来,阅读该符号的最佳方式是使用以下
[len(points)-1:2:1]。所以 len(points)-1 > 2 结果是空列表。 -
对于信息的定义,没有什么比元素“-1”更远了......但你可以手动修复它
-
@DanielMesejo 我正在寻找解决方案,提供的链接阐明了有关符号和切片如何工作的一些内容。
标签: python