【问题标题】:class instance not iterable类实例不可迭代
【发布时间】:2016-01-05 11:05:38
【问题描述】:

在我的功能中,我有:

        """
        Iterates 300 times as attempts, each having an inner-loop
        to calculate the z of a neighboring point and returns the optimal                 
        """

        pointList = []
        max_p = None

        for attempts in range(300):

            neighborList = ( (x - d, y), (x + d, y), (x, y - d), (x, y + d) )

            for neighbor in neighborList:
                z = evaluate( neighbor[0], neighbor[1] )
                point = None
                point = Point3D( neighbor[0], neighbor[1], z)
                pointList += point
            max_p = maxPoint( pointList )
            x = max_p.x_val
            y = max_p.y_val
        return max_p

我没有迭代我的类实例,点,但我仍然得到:

    pointList += newPoint
TypeError: 'Point3D' object is not iterable

【问题讨论】:

    标签: python class iterable hill-climbing


    【解决方案1】:

    问题出在这一行:

    pointList += point
    

    pointListlistpointPoint3D 实例。您只能向一个可迭代对象添加另一个可迭代对象。

    你可以用这个来修复它:

    pointList += [point]
    

    pointList.append(point)
    

    在您的情况下,您不需要将None 分配给point。您也不需要将变量绑定到新点。您可以像这样直接将其添加到列表中:

    pointList.append(Point3D( neighbor[0], neighbor[1], z))
    

    【讨论】:

      【解决方案2】:

      当您为 list 执行以下操作时 -

      pointList += newPoint
      

      它类似于调用pointList.extend(newPoint),在这种情况下newPoint需要是一个可迭代的,其元素将被添加到pointList

      如果你想要简单地将元素添加到列表中,你应该使用list.append() 方法 -

      pointList.append(newPoint)
      

      【讨论】:

        猜你喜欢
        • 2015-11-28
        • 2013-01-13
        • 1970-01-01
        • 2020-10-26
        • 1970-01-01
        • 2019-04-26
        • 1970-01-01
        • 2020-11-25
        • 2022-10-18
        相关资源
        最近更新 更多