python - AttributeError 'Nonetype' 对象没有属性。但我检查 Nonetype

标签 python list-comprehension nonetype

我得到AttributeError:'NoneType'对象没有属性'rstrip'

所以我添加了 if clist is not None: 但我不断收到相同的错误。为什么?

if clist is not None:
    result = [
        [name, clist.rstrip()] 
        for name, clist in zip(
            fragments[::group_count+1],
            fragments[group_count::group_count+1]
        )
    ]

完整回溯

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [85], in <module>
    120             fragments = fragments[1:]
    121         if clist is not None:
--> 122             result = [
    123                 [name, clist.rstrip()] 
    124                 for name, clist in zip(
    125                     fragments[::group_count+1],
    126                     fragments[group_count::group_count+1]
    127                 )
    128             ]

Input In [85], in <listcomp>(.0)
    120             fragments = fragments[1:]
    121         if clist is not None:
    122             result = [
--> 123                 [name, clist.rstrip()] 
    124                 for name, clist in zip(
    125                     fragments[::group_count+1],
    126                     fragments[group_count::group_count+1]
    127                 )
    128             ]

AttributeError: 'NoneType' object has no attribute 'rstrip'

最佳答案

试试这个。

列表理解之外的 Clist 不是 None 而是 None 中片段内的某些值,这就是您收到此错误的原因。

您需要添加如果 clist 在列表理解中不是 None,如下所示。

result = [[name, clist.rstrip()] for name, clist in zip(
            fragments[::group_count+1],
            fragments[group_count::group_count+1]
        ) if clist is not None]

关于python - AttributeError 'Nonetype' 对象没有属性。但我检查 Nonetype,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71991635/

相关文章:

python - 通过更改 'Values' 参数生成透视 Pandas 数据帧

python - Python 中推导式的长度

haskell - Haskell 列表推导式中的 OR 条件

python - TypeError:NoneType 和 str 不支持的操作数类型

Python `None` 传递到类型转换函数

python - 简单的二十一点游戏 : deck list becomes NoneType

php - 脚本语言如何使用套接字?

python - 在windows控制台直接运行python脚本

python - 使用 SQLAlchemy 更新 PostgreSQL 数组

python - 高效计算过滤列表的大小