"类型为'NoneType'的对象没有len()"错误

dmm*_*mmd 16 python web2py

我在这段代码上看到了奇怪的行为:

images = dict(cover=[],second_row=[],additional_rows=[])

for pic in pictures:
    if len(images['cover']) == 0:
        images['cover'] = pic.path_thumb_l
    elif len(images['second_row']) < 3:
        images['second_row'].append(pic.path_thumb_m)
    else:
        images['additional_rows'].append(pic.path_thumb_s)
Run Code Online (Sandbox Code Playgroud)

我的web2py应用程序给了我这个错误:

if len(images['cover']) == 0:
TypeError: object of type 'NoneType' has no len()
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚这有什么问题.也许是一些范围问题?

Mar*_*ers 15

您将新内容分配给images['cover']:

images['cover'] = pic.path_thumb_l
Run Code Online (Sandbox Code Playgroud)

这里pic.path_thumb_lNone在你的代码的一些点.

你可能想要追加:

images['cover'].append(pic.path_thumb_l)
Run Code Online (Sandbox Code Playgroud)


Inb*_*ose 9

你的问题是这样的

if len(images['cover']) == 0:

检查图像['cover']的值的长度你要做的是检查它是否有值.

改为:

if not images['cover']:

  • 无论哪种方式,你应该将你的代码更改为`if not images ['cover']:`相反,因为如果长度不是0,它将已经有一个值,这样它的pythonic更加pythonic :) (2认同)

小智 5

我们还可以在相同条件下查看类型,如果需要的话可以避免某些情况,例如

if myArray is None:
    #Do something when array has no len()
else:
    #Do something when array has elements and has len()
Run Code Online (Sandbox Code Playgroud)

就我而言,我正在数组中查找某些内容,但只有当有某些内容时,当 id 没有时,类型才是 None ,我需要创建它。希望这对某人有用。