Python - TypeError:'...' 类型的对象没有 len()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27089682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python - TypeError: object of type '...' has no len()
提问by user2971812
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))):
对于范围内的 i(min(length, len(other))):
TypeError: object of type 'CoordinateRow' has no len()
类型错误:'CoordinateRow' 类型的对象没有 len()
回答by fvannee
otheris of type CoordinateRow, which does not have a length. Use len(other.coordinate_row)instead. This is the list that does have the length property.
other是 CoordinateRow 类型,它没有长度。使用len(other.coordinate_row)来代替。这是具有长度属性的列表。
回答by Padraic Cunningham
You need to add a __len__method, then you can use len(self)and len(other):
您需要添加一个__len__方法,然后您可以使用len(self)and 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]
回答by Daniel Roseman
Iterating over a range of len(something) is very much an anti-pattern in Python. You should be iterating over the contents of the containers themselves.
迭代一系列 len(something) 是 Python 中的一种反模式。您应该迭代容器本身的内容。
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

