检查可迭代列表中的 NoneTypes

hlz*_*lzl 2 python iterable typeerror try-except nonetype

我想遍历一个可迭代列表,但要求某些元素可以是 type None

这可能看起来像这样:

none_list = [None, [0, 1]]

for x, y in none_list:
    print("I'm not gonna print anything!")
Run Code Online (Sandbox Code Playgroud)

但是,这会提示TypeError: 'NoneType' object is not iterable.

目前,我发现了错误并在NoneType之后处理。对于我的用例,这会导致大量重复的代码,因为我基本上替换了这些None值并在 for 循环中执行与最初计划相同的操作。

try:
    for x, y in none_list:
        print("I'm not gonna print anything!")
except TypeError:
    print("But I will!")
    # Deal with NoneType here
Run Code Online (Sandbox Code Playgroud)

问题: 忽略初始循环中的值TypeError并检查None值的最佳方法是什么?

Aso*_*cia 5

您可以遍历每个项目并检查None

none_list = [None, [0, 1]]
for item in none_list:
    if item is None:
        continue
    x, y = item
    print(x, y)
Run Code Online (Sandbox Code Playgroud)

或者你可以先使用列表推导来消除Nones,然后你就可以正常迭代了:

list_without_none = [item for item in none_list if item is not None]
for x, y in list_without_none:
    print(x, y)
Run Code Online (Sandbox Code Playgroud)