問題描述
基本上我的問題是說您有一個包含無"的列表,您將如何嘗試檢索列表的總和.下面是一個我試過的例子,它不起作用,我得到了錯誤:TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
.謝謝
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
推薦答案
可以使用filter
功能
>>> sum(filter(None, [1,2,3,None]))
6
根據評論更新
filter
的典型用法是 filter(func, iterable)
,但是將 None
作為第一個參數傳遞是一種特殊情況,在 Python 文檔.引用:
Typically filter
usage is filter(func, iterable)
, but passing None
as first argument is a special case, described in Python docs. Quoting:
如果function為None,則假定恒等函數,即iterable中所有為false的元素都被移除.
If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.
這篇關于使用 Python 對包含“無"的列表求和的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!