我的代码有什么问题?递归地查找嵌套列表的总和

时间:2014-03-13 19:11:25

标签: python list recursion

我试图创建一个函数,以格式返回树列表中所有整数的总和:

element 1 is an integer
element 2 is another treelist or None
element 3 is another treelist or None

ex: [1,[1,None,None],None]

所以基本上我希望我的函数将该列表中的所有整数相加并返回2.

这是我到目前为止所做的......

def sum_nested(t):
    sum = 0
    for i in t:
        if type(i) == type(None):
           sum += 0
        if type(i) == list:
           return sum_nested(i)
        else:
            sum = sum + i

    return sum  

然而,我收到错误:

builtins.TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'

当我点击无类型时,似乎无法弄清楚要做什么......有什么建议吗?

3 个答案:

答案 0 :(得分:2)

怎么样:

def sum_nested(seq):

    # Don't use `sum` as a variable name, as it shadows the builtin `sum()`
    total = 0
    for item in seq:

        # This will allow you to sum *any* iterable (tuples, for example)
        if hasattr(item, '__iter__'): 

            # Use the `+=` syntactic sugar
            total += sum_nested(item) 
        else:

            # `None or 0` evaluates to 0 :)
            total += item or 0 

    return total

答案 1 :(得分:1)

试试这个:

t = [1, [1, None, None], None]
def sum_nested(t):
    sum = 0
    for i in t:
        if type(i) is int:
            sum += 1
        elif type(i) == list:
           sum += sum_nested(i)

    return sum

print(sum_nested(t))

如果你想测试某个东西是None那么最短的形式是:

if i:

但是在你的情况下,由于你还没有改变总和,所以并不是真的有必要

答案 2 :(得分:1)

def sum_nested(seq):
    total = 0
    for item in seq:
        if hasattr(item, '__iter__'): 
            total += sum_nested(item)
            continue
        try:
            total += item
        except TypeError:
            continue
    return total

print sum_nested([2, ['text', [None, 1], [int, [True, None], 5]]])
# True counts as 1