summing only the numbers contained in a list

前端 未结 6 1770
猫巷女王i
猫巷女王i 2020-12-17 20:27

Give a method that sums all the numbers in a list. The method should be able to skip elements that are not numbers. So, sum([1, 2, 3]) should be

6条回答
  •  北海茫月
    2020-12-17 21:04

    use filter and isinstance like this

    >>> test = [1,2,3,4,5,6,"A","B"]
    >>> sum(filter(lambda x:isinstance(x,int),test))
    21
    >>> 
    

提交回复
热议问题