一个值数组中非序列的Python迭代

2024-04-26 11:33:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个代码来返回点列表中某个点的坐标。点列表类定义如下:

class Streamline:

## Constructor
#  @param ID     Streamline ID
#  @param Points list of points in a streamline
def __init__ ( self, ID, points):
    self.__ID           = ID
    self.__points        = points

## Get all Point coordinates
#  @return Matrix of Point coordinates
def get_point_coordinates ( self ):
    return np.array([point.get_coordinate() for point in self.__points])

^{pr2}$

问题是,我通过在点列表中定义一个点来开始我的代码。再往前走一点,我调用函数get_point_coordinates,对点列表进行迭代会产生以下错误:

return np.array([point.get_coordinate() for point in self.__points])
TypeError: iteration over non-sequence

我需要找到一种方法来绕过这个错误,并且只返回一个带有点坐标的1x2矩阵。在

我看过this question,但没什么用。在


Tags: of代码inselfid列表getreturn
1条回答
网友
1楼 · 发布于 2024-04-26 11:33:13
  1. 使用序列而不是单点调用Streamline构造函数:sl = Streamline(ID, [first_point])

  2. 或者确保构造函数将单点设置为iterable:

    class Streamline:
        def __init__ ( self, ID, first_point):
            self.__ID     = ID
            self.__points = [first_point]
    
  3. 编写构造函数以接受一个单点(Streamline(ID, point1))和一个点序列(Streamline(ID, [point1, point2, ...]))是个坏主意。如果你想的话,你可以做

    ^{2美元
  4. 比3强。将通过*对参数中给定的点进行解压,以启用Streamline(ID, point1)和{}。在

    class Streamline:
        def __init__ ( self, ID, *points):
            self.__ID     = ID
            self.__points = points
    

相关问题 更多 >