【发布时间】:2020-10-10 00:03:33
【问题描述】:
我想循环遍历一个可迭代的列表,但要求某些元素可以是 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 值的最佳方法是什么?
【问题讨论】:
-
你想如何处理
Nones?你只是想忽略它们吗?在这种情况下,您可以使用filter。 -
@PaulM。我想用自定义值(如
-1)替换循环内的Nones。
标签: python typeerror iterable nonetype try-except