【问题标题】:"object of type 'NoneType' has no len()" error“'NoneType' 类型的对象没有 len()”错误
【发布时间】:2012-08-02 17:58:32
【问题描述】:

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

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()

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

【问题讨论】:

  • 您正在询问包含 None 的变量的长度。 None 是一个没有长度的特殊值(类型为 NoneType)。在检查某物的长度之前,请先检查以确保它的值不为“None”。

标签: python web2py


【解决方案1】:

你给images['cover']分配了一些新的东西:

images['cover'] = pic.path_thumb_l

在您的代码中,pic.path_thumb_lNone

您可能打算改为追加:

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

【讨论】:

    【解决方案2】:

    你的问题是

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

    检查 images['cover'] 值的 LENGTH 你的意思是检查它是否有一个值。

    改为这样做:

    if not images['cover']:

    【讨论】:

    • 实际上是由于将一些“无”分配给图像['cover'](正如 Martjin 所指出的那样)。不过谢谢!
    • 在你的帖子中你说if len(images['cover']) == 0:这行给了你错误......
    • 无论哪种方式,您都应该将代码更改为 if not images['cover']:,因为如果长度不为 0,则它已经有一个值,这样就更 Pythonic 了 :)
    • 是的。在 for 内部的第二次迭代中,images['cover'] 类型为“None”,因为第一次迭代为其分配了一些“None”值。
    • 哦,是的,这是真的。会这样做!谢谢:)
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-06-14
      • 1970-01-01
      • 1970-01-01
      • 2013-03-14
      • 1970-01-01
      • 1970-01-01
      • 2019-10-28
      • 1970-01-01
      相关资源
      最近更新 更多