【问题标题】:Check for NoneTypes in a list of iterables检查可迭代列表中的 NoneTypes
【发布时间】: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


【解决方案1】:

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

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

或者你可以先使用列表推导来消除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)

【讨论】:

  • 谢谢,第一个选项正是我想做的!不知何故没有考虑迭代单个 item 而不是单个元素。
  • 是的,您可以尝试x, y = None 并得到相同的错误,但如果您尝试x = None,它将毫无问题地运行。
【解决方案2】:

我实际上发现filter 非常方便:

for x,y in filter(None, none_list):
    do_stuff()

【讨论】:

  • 我喜欢这种方法,它非常干净!不过,我希望能够在之后处理Nones,所以我接受了另一个答案。还是谢谢!
  • 请注意,这将过滤所有 falsy 值:>>> list(filter(None, ["", 0, False, None, 3])) -> [3]
猜你喜欢
  • 1970-01-01
  • 2019-07-05
  • 2018-07-27
  • 2021-11-09
  • 1970-01-01
  • 2021-10-29
  • 1970-01-01
  • 1970-01-01
  • 2017-09-29
相关资源
最近更新 更多