检查可迭代列表中的 NoneTypes
Check for NoneTypes in a list of iterables
我想遍历可迭代列表,但要求某些元素可以是 None
.
类型
这可能看起来像这样:
none_list = [None, [0, 1]]
for x, y in none_list:
print("I'm not gonna print anything!")
但是,这会提示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
问题:
在初始循环中忽略 TypeError
并检查 None
值的最佳方法是什么?
您可以遍历每个项目并检查 None
:
none_list = [None, [0, 1]]
for item in none_list:
if item is None:
continue
x, y = item
print(x, y)
或者你可以先使用列表理解来消除None
s,然后你可以正常迭代:
list_without_none = [item for item in none_list if item is not None]
for x, y in list_without_none:
print(x, y)
我实际上发现 filter
对此非常方便:
for x,y in filter(None, none_list):
do_stuff()
我想遍历可迭代列表,但要求某些元素可以是 None
.
这可能看起来像这样:
none_list = [None, [0, 1]]
for x, y in none_list:
print("I'm not gonna print anything!")
但是,这会提示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
问题:
在初始循环中忽略 TypeError
并检查 None
值的最佳方法是什么?
您可以遍历每个项目并检查 None
:
none_list = [None, [0, 1]]
for item in none_list:
if item is None:
continue
x, y = item
print(x, y)
或者你可以先使用列表理解来消除None
s,然后你可以正常迭代:
list_without_none = [item for item in none_list if item is not None]
for x, y in list_without_none:
print(x, y)
我实际上发现 filter
对此非常方便:
for x,y in filter(None, none_list):
do_stuff()