空类型物体没有长度() (Kōng lèixíng wùtǐ méiyǒu chǎngdù ())

2024-04-25 18:58:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我看到这段代码有奇怪的行为:

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)

我的web2py应用程序出现以下错误:

if len(images['cover']) == 0:
TypeError: object of type 'NoneType' has no len()

我想不出这里面有什么问题。可能是范围问题?


Tags: path代码forlenifcoverdictadditional
3条回答

第一次分配:images['cover'] = pic.path_thumb_l时,它将最初存储在images['cover']中的空列表的值替换为pic.path_thumb_l的值,即None

也许这一行的代码必须是images['cover'].append(pic.path_thumb_l)

您为images['cover']分配了新内容:

images['cover'] = pic.path_thumb_l

其中pic.path_thumb_l在代码中的某个时刻是None

你可能想加上:

images['cover'].append(pic.path_thumb_l)

你的问题是

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

检查图像值的长度[“cover”]要做的是检查它是否有值。

请改为:

if not images['cover']:

相关问题 更多 >