Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

Sum a list which contains 'None' using Python

Basically my question is say you have an list containing 'None' how would you try retrieving the sum of the list. Below is an example I tried which doesn't work and I get the error: TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'. Thanks

def sumImport(self):
    my_list = [[1,2,3,None],[1,2,3],[1,1],[1,1,2,2]]
    k = sum(chain.from_iterable(my_list))
    return k
question from:https://stackoverflow.com/questions/12229902/sum-a-list-which-contains-none-using-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...