gpt4 book ai didi

python - 检查可迭代列表中的 NoneTypes

转载 作者:行者123 更新时间:2023-12-05 09:09:25 24 4
gpt4 key购买 nike

我想遍历可迭代列表,但要求某些元素的类型可以是 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,然后您可以正常迭代:

list_without_none = [item for item in none_list if item is not None]
for x, y in list_without_none:
print(x, y)

关于python - 检查可迭代列表中的 NoneTypes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62475256/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com