[英]TypeError: object of type 'int' has no len() in python
Here is my code first:这是我的代码:
res = []
for x in range(9):
if x == 0:
res.append([1])
elif x == 1:
res.append([1,1])
print(res)
else:
l=[]
for y in range(len(res[x-1])):
if y == 0:
l.append(1)
else:
l.append(res[x-1][y] + res[x-1][y-1])
l.append(1)
res.append(1)
and I meet the problem.我遇到了这个问题。 Then I change a little bit of code like this:
然后我像这样更改了一点代码:
res = [[1],[1,1]]
for i in range(2,9):
res.append([1])
for j in range(len(res[i-1])):
if j > 0:
res[i].append(int(res[i-1][j-1]+res[i-1][j]))
res[i].append(1)
print(res)
and the error has gone.并且错误消失了。 I am quite wondering what is wrong inside?
我很想知道里面有什么问题?
Let's say you have my_var = 5
.假设您有
my_var = 5
。 By running len(my_var)
you will get an error, because variable my_var
is an int (short for an integer).通过运行
len(my_var)
你会得到一个错误,因为变量my_var
是一个 int (整数的缩写)。
However, if you have my_var = [5]
, your command len(my_var)
will work because it is a list.但是,如果您有
my_var = [5]
,您的命令len(my_var)
将起作用,因为它是一个列表。
Similarly in your code, as khelwood says, if you have l.append(1)
, your variable l
will contain an integer 1. This will raise an error if you call len()
on this element.同样,在您的代码中,正如 khelwood 所说,如果您有
l.append(1)
,则您的变量l
将包含一个整数 1。如果您对此元素调用len()
,则会引发错误。 If you want to append something to a list then find its length later, make sure it is not an int but a list, try l append([1])
.如果您想将某些内容附加到列表然后稍后找到它的长度,请确保它不是 int 而是列表,请尝试
l append([1])
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.