Python 判断变量是否为 NoneType

Sib*_*ibi -1 python nonetype

在下面的循环中,最初lines_hp[0]不是NoneType. 但经过一些操作后,它会变成NoneType,我想在发生这种情况时打破循环。经过一些循环迭代后,lines_hp[0]更改为NoneType,但是当我想使用 来识别它时lines_hp[0] is not None,我收到错误:'NoneType' object has no attribute '__getitem__'。我怎样才能解决这个问题?

while lines_hp[0] is not None:
    print lines_hp[0] is not None
    #some operation to change lines_hp[0]
Run Code Online (Sandbox Code Playgroud)

我已经了解了许多有关如何检测 NoneType 项目的问题和答案,但我仍然收到上述错误。

Wil*_*sem 6

不是过去lines_hp[0]None而是lines_hp现在None。Python 抱怨您想从None对象(如None[0])获取索引,但失败了。

您应该首先检查一下:

while lines_hp is not None and lines_hp[0] is not None:
    print lines_hp[0] is not None
    #some operation to change lines_hp[0]
Run Code Online (Sandbox Code Playgroud)