对具有一个值

时间:2016-03-16 09:59:48

标签: python list iteration

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

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])

使用

class Point:
## Constructor
#  @param ID     Streamline ID
#  @param cor    List of Coordinates
#  @param vel    List of velocity vectors (2D)
def __init__ ( self, ID,  coord, veloc):
    self.__ID           = ID
    self.set_coordinate( coord )
    self.set_velocity( veloc )

问题在于我通过在点列表中定义一个Point的Streamline来启动我的代码。稍微开始我调用函数get_point_coordinates,迭代点列表会引发以下错误:

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

我需要找到一种绕过这个错误的方法,然后整齐地返回一个带点坐标的1x2矩阵。

我看过this question,但它没有用处。

1 个答案:

答案 0 :(得分:0)

  1. 使用序列而不是单个点调用Streamline构造函数:sl = Streamline(ID, [first_point])

  2. 或者确保构造函数使单点可迭代:

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

    from collections import Iterable
    class Streamline:
        def __init__ ( self, ID, first_point):
            self.__ID     = ID
            self.__points = points if isinstance(points, Iterable) else [points]
    
  4. 优于3.将通过*解包参数中的点数以启用Streamline(ID, point1)Streamline(ID, point1, point2, ...)

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