python 在 cast\addition 之前处理 Nonetype [英] python dealing with Nonetype before cast\addition

查看:21
本文介绍了python 在 cast\addition 之前处理 Nonetype的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从数据库中提取一行并将字段(大约 15 个)相加以获得总数.但是有些字段的值会是 Null,这会导致字段添加错误(TypeError: unsupported operand type(s) for +: 'NoneType' and 'int')

I'm pulling a row from a db and adding up the fields (approx 15) to get a total. But some field values will be Null, which causes an error in the addition of the fields (TypeError: unsupported operand type(s) for +: 'NoneType' and 'int')

现在,对于每个字段,我获取字段值并将其设置为x#",然后检查它是否为无",如果是,则将x#"设置为 0.

Right now, with each field, I get the field value and set it to 'x#', then check if it is None and if so set 'x#' to 0.

不是很优雅……关于在 python 中处理这个问题的更好方法有什么建议吗?

Not very elegant...any advice on a better way to deal with this in python?

抄送

推荐答案

您可以像这样轻松完成:

You can do it easily like this:

result = sum(field for field in row if field)

这篇关于python 在 cast\addition 之前处理 Nonetype的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆