class 实例不可迭代
class instance not iterable
在我的函数中,我有:
"""
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
我没有遍历我的 class 实例,但是我仍然得到:
pointList += newPoint
TypeError: 'Point3D' object is not iterable
问题出在这一行:
pointList += point
pointList
是一个 list
而 point
是一个 Point3D
实例。您只能将另一个可迭代对象添加到可迭代对象中。
你可以用这个修复它:
pointList += [point]
或
pointList.append(point)
在您的情况下,您不需要将 None
分配给 point
。您也不需要将变量绑定到新点。您可以像这样将其直接添加到列表中:
pointList.append(Point3D( neighbor[0], neighbor[1], z))
当您对 list
-
执行以下操作时
pointList += newPoint
它类似于调用 pointList.extend(newPoint)
,在这种情况下 newPoint
需要是一个可迭代的,其元素将被添加到 pointList
.
如果您只是想简单地将元素添加到列表中,您应该使用 list.append()
方法 -
pointList.append(newPoint)
在我的函数中,我有:
"""
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
我没有遍历我的 class 实例,但是我仍然得到:
pointList += newPoint
TypeError: 'Point3D' object is not iterable
问题出在这一行:
pointList += point
pointList
是一个 list
而 point
是一个 Point3D
实例。您只能将另一个可迭代对象添加到可迭代对象中。
你可以用这个修复它:
pointList += [point]
或
pointList.append(point)
在您的情况下,您不需要将 None
分配给 point
。您也不需要将变量绑定到新点。您可以像这样将其直接添加到列表中:
pointList.append(Point3D( neighbor[0], neighbor[1], z))
当您对 list
-
pointList += newPoint
它类似于调用 pointList.extend(newPoint)
,在这种情况下 newPoint
需要是一个可迭代的,其元素将被添加到 pointList
.
如果您只是想简单地将元素添加到列表中,您应该使用 list.append()
方法 -
pointList.append(newPoint)