我从数据库中拉出一行并将字段(大约15个)相加以得到总数。但是一些字段值将为Null,这会导致添加字段时出错(TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
)
现在,对于每个字段,我得到字段值并将其设置为'x#',然后检查它是否为None,如果是,则将'x#'设置为0.
不是很优雅......有什么建议可以更好地解决这个问题吗?
CC
答案 0 :(得分:13)
你可以这样轻松地做到:
result = sum(field for field in row if field)
答案 1 :(得分:1)
另一个(更好?)选项是在数据库中执行此操作。您可以使用COALESCE更改数据库查询以将NULL映射为0。
假设您有一个包含名为col1,col2,col3的整数列的表,它可以接受NULL。
选项1:
SELECT coalesce(col1, 0) as col1, coalesce(col2, 0) as col2, coalesce(col3, 0) as col3
FROM your_table;
然后在返回的行上使用Python中的sum(),而不必担心是否存在。
选项2: 对数据库中的列求和并在查询中返回总数:
SELECT coalesce(col1, 0) + coalesce(col2, 0) + coalesce(col3, 0) as total
FROM your_table;
在Python中没有更多的事情要做。第二个选项的一个优点是,您可以在查询中选择不属于总和的其他列(您可能在表中有其他列并且正在进行多个查询以获取表的不同列?)
答案 2 :(得分: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 ) )
答案 3 :(得分:0)
total = 0.0
for f in fields:
total += f or 0.0