You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

坐标浮点值索引异常:平移点列表触发TypeError错误求助

问题:平移坐标点时触发TypeError错误

我有如下点列表:

points = [[6033.02, -24791.2], [7008.29, -24257.0], [7128.66, -23434.0], [7235.19, -22899.3], [6590.0, -22308.7]]

以及中心点:

centre = [37621.265, -32837.66499999999]

我用下面的函数对这些点做平移操作:

def translate(center, points):
    new_points_x = []
    new_points_y = []
    new_points = []
    for i in points:
        # print(str(i[0]))
        new_points_x.append(i[0]-center[0]) 
    
    for i in points:
        new_points_y.append(i[1]-center[1])

    for i in range(0,len(new_points_x)):
        new_points.append([new_points_x[i], new_points_y[i]])

    return new_points 

运行时触发错误:

TypeError: 'float' object is not subscriptable

错误原因

你调用translate函数时参数顺序传反了。函数定义的参数顺序是translate(center, points),但你大概率写成了translate(points, centre)。此时函数里的center参数接收的是points列表,而points参数接收的是centre这个仅含两个float元素的列表。

当执行第一个循环for i in points:时,这里的points实际是centre,遍历得到的i是单个float值(比如37621.265),这时尝试访问i[0]自然会抛出“float不可下标访问”的错误。

解决方法

  1. 修正调用顺序:按照函数定义的参数顺序传入,正确调用示例:
result = translate(centre, points)
print(result)
  1. 优化函数实现(可选):你的函数可以简化,不用分三次循环,一次循环就能完成:
def translate(center, points):
    new_points = []
    for x, y in points:
        new_x = x - center[0]
        new_y = y - center[1]
        new_points.append([new_x, new_y])
    return new_points

# 或者用列表推导式更简洁:
def translate(center, points):
    return [[x - center[0], y - center[1]] for x, y in points]

内容的提问来源于stack exchange,提问作者user110920

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 21:05:24