2015-10-08 64 views
2

在我的FUNC,我有:類的實例並不可迭代

 """ 
     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 

回答

5

的問題是這條線:

pointList += point 

pointListlistpointPoint3D實例。您只能將其他迭代添加到迭代器中。

您可以使用此解決它:

pointList += [point] 

pointList.append(point) 

你的情況,你不需要指定Nonepoint。您也不需要將變量綁定到新的點。您可以直接將它添加到列表中是這樣的:

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

當你下了list -

pointList += newPoint 

它類似於調用pointList.extend(newPoint),在這種情況下newPoint需要有一個可迭代,其元素將被添加到pointList

如果你想要的是簡單地將元素添加到列表中,你應該使用list.append()方法 -

pointList.append(newPoint) 
相關問題