summing only the numbers contained in a list

前端 未结 6 1753
猫巷女王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:09

    def filtersum(L):
        if not L: return 0
        if not isinstance(L[0], int): return filtersum(L[1:])
        return L[0] + filtersum(L[1:])
    

    Output:

    In [28]: filtersum([1,2,3])
    Out[28]: 6
    
    In [29]: filtersum([1,'A', 2,3])
    Out[29]: 6
    

提交回复
热议问题