简体   繁体   English

Python - TypeError:类型为'...'的对象没有len()

[英]Python - TypeError: object of type '…' has no len()

Here is a class: 这是一堂课:

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

This is a part of my program: 这是我的计划的一部分:

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)

But I'm geting an error at "cr12 = cr.weave(cr2)": 但我在“cr12 = cr.weave(cr2)”中发现错误:

for i in range(min(length, len(other))): for in in range(min(length,len(other))):

TypeError: object of type 'CoordinateRow' has no len() TypeError:“CoordinateRow”类型的对象没有len()

You need to add a __len__ method, then you can use len(self) and len(other) : 你需要添加一个__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]

Iterating over a range of len(something) is very much an anti-pattern in Python. 迭代一系列len(某事)在Python中是非常反模式的。 You should be iterating over the contents of the containers themselves. 您应该迭代容器本身的内容。

In your case, you can just zip the lists together and iterate over that: 在您的情况下,您可以将列表压缩在一起并迭代:

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

other is of type CoordinateRow, which does not have a length. other是CoordinateRow类型,没有长度。 Use len(other.coordinate_row) instead. 请改用len(other.coordinate_row) This is the list that does have the length property. 这是具有length属性的列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM