Python如何检测浮点列表中的None值并编写正确的布尔校验函数
代码问题原因
any(data)的作用是校验可迭代对象中是否存在布尔值为真的元素,仅会返回True/False,因此any(data) == None的判断永远为假,是核心逻辑错误- 检测到None的分支缺少
return关键字,仅写False不会返回有效值,函数会默认返回None - 判断
None的规范写法是is None而非== None,避免被自定义对象的相等判断逻辑干扰 - 注释中的列表推导误用了全局变量
group_temps,没有使用传入的参数data,会引发作用域错误
正确实现代码
def none_checker_function(data): # 只要有一个元素是None就判定为存在None has_none = any(item is None for item in data) if has_none: print("none checker found NoneTypes!") return False else: print("none checker did Not Find NoneTypes!") return True
测试结果
对三个示例列表调用函数的输出如下:
# 调用none_checker_function(group_temps1) none checker found NoneTypes! False # 调用none_checker_function(group_temps2) none checker found NoneTypes! False # 调用none_checker_function(group_temps3) none checker did Not Find NoneTypes! True
内容的提问来源于stack exchange,提问作者bbartling
相关产品推荐
相关产品推荐

