2016-03-16 29 views
1

我正在編寫一個代碼以返回點列表中某個點的座標。點類的列表定義如下:用一個值對數組中的非序列進行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]) 

隨着

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) 

的事情是,我通過定義在點列表中的一個點流線型開始我的代碼。走了一小段路上,我調用該函數get_point_coordinates和迭代超分的名單引發了以下錯誤:

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

我需要找到一種方法來繞過這個錯誤,並整齊地用積分返還只是一個1x2的矩陣座標。我看過this question,但它不是很有幫助。

+1

然後'自.__ points'不能是迭代。那麼「self .__ points」的類型是什麼? –

+0

發佈您如何實例化Streamline對象。 – loutre

回答

0
  1. 要麼調用流線型構造與序列而不是單點: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