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

AttributeError 'Nonetype' object has no attribute. But i check for Nonetype

我得到AttributeError: 'NoneType' object has no attribute '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 out of the list comprehension 不是 None 而是 None 中片段内的一些值,这就是你得到这个错误的原因。

您需要添加 if clist is not None inside list comprehension 如下所示。

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