gpt4 book ai didi

python - 类实例不可迭代

转载 作者:行者123 更新时间:2023-11-28 19:54:52 26 4
gpt4 key购买 nike

在我的函数中,我有:

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

最佳答案

问题是这一行:

pointList += point

pointList 是一个 listpoint 是一个 Point3D 实例。您只能将另一个可迭代对象添加到可迭代对象。

你可以用这个修复它:

pointList += [point]

pointList.append(point)

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

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

关于python - 类实例不可迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33005398/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com