2014-11-23 91 views
2

這裏是一個類:的Python - 類型錯誤:類型的 '...' 對象沒有LEN()

class CoordinateRow(object): 

def __init__(self): 
    self.coordinate_row = [] 

def add(self, input): 
    self.coordinate_row.append(input) 

def weave(self, other): 
    result = CoordinateRow() 
    length = len(self.coordinate_row) 
    for i in range(min(length, len(other))): 
     result.add(self.coordinate_row[i]) 
     result.add(other.coordinate_row[i]) 
    return result 

這是我計劃的一部分:

def verwerk_regel(regel): 
cr = CoordinateRow() 
coordinaten = regel.split() 
for coordinaat in coordinaten: 
    verwerkt_coordinaat = verwerk_coordinaat(coordinaat) 
    cr.add(verwerkt_coordinaat) 
cr2 = CoordinateRow() 
cr12 = cr.weave(cr2) 
print cr12 

def verwerk_coordinaat(coordinaat): 
coordinaat = coordinaat.split(",") 
x = coordinaat[0] 
y = coordinaat[1] 
nieuw_coordinaat = Coordinate(x) 
adjusted_x = nieuw_coordinaat.pas_x_aan() 
return str(adjusted_x) + ',' + str(y) 

但我米在 「CR12 = cr.weave(CR 2)」 歌廳一個錯誤:在範圍

對於i(分鐘(長度,LEN(其他))):

類型錯誤:類型的對象 'CoordinateRow' 沒有升en()

+0

不知道你的問題是什麼。你在'CoordinateRow'的實例上調用'len',但該類沒有定義'__len__'函數。 – 2014-11-23 13:57:50

回答

0

other是類型CoordinateRow,它沒有長度。改爲使用len(other.coordinate_row)。這是具有長度屬性的列表。

3

您需要添加一個__len__方法,那麼你可以使用len(self)len(other)

class CoordinateRow(object): 
    def __init__(self): 
     self.coordinate_row = [] 

    def add(self, input): 
     self.coordinate_row.append(input) 

    def __len__(self): 
     return len(self.coordinate_row) 

    def weave(self, other): 
     result = CoordinateRow() 
     for i in range(min(len(self), len(other))): 
      result.add(self.coordinate_row[i]) 
      result.add(other.coordinate_row[i]) 
     return result 
In [10]: c = CoordinateRow()  
In [11]: c.coordinate_row += [1,2,3,4,5]  
In [12]: otherc = CoordinateRow()  
In [13]: otherc.coordinate_row += [4,5,6,7]  
In [14]:c.weave(otherc).coordinate_row 
[1, 4, 2, 5, 3, 6, 4, 7] 
+0

我試過你的方法,但它給錯誤如下:TypeError:'NoneType'對象不可迭代 – 2016-03-21 06:50:46

2

迭代一個範圍LEN(東西)的非常多了一個Python反模式。你應該迭代容器本身的內容。

在你的情況,你可以只是壓縮列表在一起,迭代是:

def weave(self, other): 
    result = CoordinateRow() 
    for a, b in zip(self.coordinate_row, other.coordinate_row): 
     result.add(a) 
     result.add(b) 
    return result 
相關問題