You can use filter
function
>>> sum(filter(None, [1,2,3,None]))
6
Updated from comments
Typically filter
usage is filter(func, iterable)
, but passing None
as first argument is a special case, described in Python docs. Quoting:
If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…