【问题标题】:TypeError: range indices must be integers or slices, not tupleTypeError:范围索引必须是整数或切片,而不是元组
【发布时间】:2019-11-21 06:32:56
【问题描述】:

我的代码中有两个嵌套的 for 循环,但一个有效,另一个无效,它们也是相同的,它在我的脑海中发挥作用

此代码有效

def nearest(furthestpoints,lastpoints,lastIDs,currentpoints,img,threshold = 30):
    currentIDs = np.empty(0,dtype = float)
    normList = np.empty(0,dtype = float)

    for i in range(0,len(currentpoints)):
        for a in range(0,len(lastpoints)):
            normList = np.append(normList,np.linalg.norm(currentpoints[i,:] - lastpoints[a,:]))```

但是这段代码会产生错误

File "/home/oliver/tracker.py", line 22, in getLostPoints
    normList = np.append(normList,np.linalg.norm(current[i,:] - last[a,:]))
TypeError: range indices must be integers or slices, not tuple
def getLostPoints(last,lastIDs,current,threshold = 50):

    normList = np.empty(0,dtype = float)
    goodIDs = np.empty(0,dtype = int)
    lostPoints = np.empty((2,0),dtype = float)

    for i in range(0,len(last)):
        for a in range(0,len(current)):
            normList = np.append(normList,np.linalg.norm(current[i,:] - last[a,:]))

        if min(normList) < threshold:
            indexMin = np.argmin(normList)
            goodIDs = np.append(goodIDs,lastIDs[indexMin])
        normList = np.empty(0,dtype = float) 

这些只是循环,这段代码还有更多内容

输入数组的形状为(n,2) 其中n 是点数

【问题讨论】:

  • 您的切片是:current[i,:] - last[a,:]。你的意思是他们是: current[i:] - last[a:] 没有逗号。
  • 这不起作用,因为我试图索引的数组是形状 (5,2) 你建议的会产生广播错误 ValueError: 操作数不能与形状一起广播 (5,) (5, 2)

标签: python python-3.x numpy


【解决方案1】:

我没有足够的声誉来发表评论,所以我必须发布这个作为答案。

首先,你有:

    for i in range(0,len(current)):
        for a in range(0,len(current)):

你的意思是:

    for i in range(0,len(current)):
        for a in range(0,len(last)):

这将遵循与您的有效方法相同的模式。

您是否尝试过在第二种方法中打印ia 作为完整性检查以及打印输入的特征(形状等)?这不是最有说服力的调试方式,但打印值以确保它们符合您的预期可能会很有见地。

【讨论】:

  • 哎呀对不起我的意思是它不会改变错误虽然我改变了帖子我也做了所有的调试事情我只是不想把它放在代码中让它看起来很乱但是我和a 都是
【解决方案2】:

当我在主循环中调用代码时发现问题是一个简单的错误 现在可以正常使用了,感谢您的回答

【讨论】:

    猜你喜欢
    • 2017-03-11
    • 1970-01-01
    • 2019-11-23
    • 2017-10-02
    • 2018-12-29
    • 2019-09-15
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    相关资源
    最近更新 更多