Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
TypeError:类型为'的对象;int';在python中没有len()_Python_Python 3.x - Fatal编程技术网

TypeError:类型为'的对象;int';在python中没有len()

TypeError:类型为'的对象;int';在python中没有len(),python,python-3.x,Python,Python 3.x,以下是我的代码: 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(

以下是我的代码:

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)
我遇到了问题。然后我修改了一些代码,如下所示:

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)
错误已经消失了。
我很想知道里面出了什么问题?

假设您有
my_var=5
。通过运行
len(my_var)
您将得到一个错误,因为变量
my_var
是一个int(整数的缩写)

但是,如果您有
my\u var=[5]
,您的命令
len(my\u var)
将起作用,因为它是一个列表

类似地,在代码中,正如khelwood所说,如果有
l.append(1)
,那么变量
l
将包含一个整数1。如果在此元素上调用
len()
,则会引发错误。如果要将某个内容附加到列表中,然后稍后查找其长度,请确保它不是int而是列表,请尝试
l append([1])

您有
res.append(1)
您的第一个版本。这意味着
res
包含一个int。因此
len(res[x-1])
试图获取int的长度,这就是错误。