首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TypeError:列表索引必须是整数或切片,而不是节点#节点是类

TypeError:列表索引必须是整数或切片,而不是节点#节点是类
EN

Stack Overflow用户
提问于 2019-02-24 03:36:03
回答 1查看 197关注 0票数 0

我需要访问类值的帮助。

这是我的Node类。

代码语言:javascript
复制
class Node():
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.parent = None

这是我访问上面的类的另一个类。

代码语言:javascript
复制
class RRT():
    def __init__(self, start, goal, obstacle_list):
        self.start = Node(start[0], start[1])  # start node for the RRT
        self.goal = Node(goal[0], goal[1])     # goal node for the RRT
        self.obstacle_list = obstacle_list     # list of obstacles 
        self.node_list = []    # list of nodes added while creating the RRT
    ...

我将start存储在我的RRT类中的另一个函数中,如下所示的self.node_list = [self.start]

代码语言:javascript
复制
    def getNearestNode(self, random_point):
        minDist = 1e5
        for ii in self.node_list:
            nodePt = [None, None]
            # error occurs at line below
            nodePt[0] = self.node_list[ii].x
            nodePt[1] = self.node_list[ii].y
            # this function takes 2 coordinate lists and computes the distance
            dist = self.calcDistNodeToPoint(nodePt, random_point)
            if dist < minDist:
                minDist = dist
                index = ii
        return index

我收到此错误消息TypeError: list indices must be integers or slices, not Node

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-24 03:39:54

Python for循环是for-each循环。ii是元素本身,而不是索引。

您应该执行以下操作:

代码语言:javascript
复制
nodePt[0] = ii.x
nodePt[1] = ii.y

或者更好的做法是,在此之前不要定义nodePt,只需定义:

代码语言:javascript
复制
nodePt = ii.x, ii.y
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54845427

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档