【问题标题】:Listing python tuples, the edge case [duplicate]列出python元组,边缘情况[重复]
【发布时间】: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


【解决方案1】:

这个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

【讨论】:

  • 这与我所追求的非常接近,但这里的结果是[2 2] [4 4] 而不是[(2, 2), (4, 4)]。但是,我能够在您的解决方案的基础上进行整理。我将编辑我的帖子并将其标记为解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-25
  • 1970-01-01
  • 1970-01-01
  • 2017-05-26
  • 1970-01-01
  • 1970-01-01
  • 2015-02-15
相关资源
最近更新 更多