简体   繁体   English

类型错误:“int”类型的对象在 python 中没有 len()

[英]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.

相关问题 TypeError:类型为'int'的对象没有len()-Python / Pygame - TypeError: object of type 'int' has no len() - Python/Pygame TypeError:“int”类型的 object 在 python(密码生成器)中没有 len() - TypeError: object of type 'int' has no len() in python (Password Generator) FLASK PYTHON:TypeError:“int”类型的 object 没有 len() - FLASK PYTHON: TypeError: object of type 'int' has no len() TypeError:类型为'int'的对象没有len()? - TypeError: object of type 'int' has no len()? 类型错误:“int”类型的对象没有 len() *减法* - TypeError: object of type 'int' has no len() *subtraction* Python - len function 没有按预期工作,并给我错误“TypeError: object of type 'int' has no len()” - Python - len function not working as expected, and giving me the error "TypeError: object of type 'int' has no len()" Python-TypeError:“单元格”类型的对象没有len() - Python - TypeError: object of type 'Cell' has no len() Python - TypeError:类型为'...'的对象没有len() - Python - TypeError: object of type '…' has no len() Python-TypeError:“ NoneType”类型的对象没有len() - Python - TypeError: object of type 'NoneType' has no len() Python TypeError:“NoneType”类型的对象没有 len() - Python TypeError: object of type 'NoneType' has no len()
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM