python - 列出 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)]
解决方案
这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
推荐阅读
- python-3.x - requests_html 渲染方法继续导致超时
- javascript - 基于时间的动画背景
- ruby-on-rails - searchkick 400 Searchkick::InvalidQueryError 建议
- android - 如何创建在被点击时播放音频文件的通知?
- c - 输出一个数是否可被 3 整除的 C 程序
- reactjs - axios 返回缓存数据
- rust - arduino 目标的货物测试失败,箱子中有重复的 lang 项
- javascript - 未定义 chrome 扩展 $ 中的 jQuery | 如何在 chrome 扩展中使用 jQuery?
- .htaccess - 将所有子域重定向到另一个文件
- html - 汉堡菜单的一个元素覆盖了一个子元素