Python处理类型转换前的None类型
我从数据库中提取一行数据,然后把大约15个字段的值加起来,想得到一个总和。但是,有些字段的值是空的(也就是Null),这就导致在加这些字段的时候出现错误(TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
)。
现在,我对每个字段的值进行处理,先把它的值赋给一个变量(比如叫'x#'),然后检查这个值是不是None,如果是的话,就把'x#'设为0。
这样做不是很优雅……有没有更好的方法来处理这个问题呢?
cc
4 个回答
0
这是一个比较笨重的版本。
total = (a if a is not None else 0) + (b if b is not None else 0) + ...
这是另一个选择。
def ifnull(col,replacement=0):
return col if col is not None else replacement
total = ifnull(a) + ifnull(b) + ifnull(c) + ...
这是又一个选择。
def non_null( *fields ):
for f in fields:
if f is not None:
yield f
total = sum( non_null( a, b, c, d, e, f, g ) )
1
另一个(可能更好的)选择是在数据库中处理这个问题。你可以修改你的数据库查询,用 COALESCE 把 NULL 转换成 0。
假设你有一个表,里面有几个可以接受 NULL 的整数列,分别叫 col1、col2 和 col3。
选项 1:
SELECT coalesce(col1, 0) as col1, coalesce(col2, 0) as col2, coalesce(col3, 0) as col3
FROM your_table;
然后在 Python 中对返回的行使用 sum(),这样就不用担心里面有没有 None 了。
选项 2:在数据库中对这些列求和,并在查询中返回总和:
SELECT coalesce(col1, 0) + coalesce(col2, 0) + coalesce(col3, 0) as total
FROM your_table;
这样在 Python 中就不需要再做其他操作了。第二个选项的一个好处是,你可以在查询中选择其他不参与求和的列(你可能在表中还有其他列,并且需要多次查询来获取不同的列数据?)
13
你可以像这样简单地做到:
result = sum(field for field in row if field)