【问题标题】:what's wrong with my code? recursively finding sum of nested list我的代码有什么问题?递归查找嵌套列表的总和
【发布时间】:2014-04-18 18:37:48
【问题描述】:

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

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'

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

【问题讨论】:

  • sum += 0 等于 sum,因此 if 块是多余的。

标签: python list recursion


【解决方案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:

但在你的情况下,这并不是真正必要的,因为无论如何你都没有改变 sum

【讨论】:

    【解决方案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
    

    【讨论】:

    • 嘿,这行得通,所以谢谢你,但我不明白你是如何做出最后第二条语句“total += item or 0. 它怎么知道什么时候将 0 添加到总数中?
    • @user3050527: None''{}0[],当然还有False 是 Python 中的“false-y”值。这意味着它们在逻辑表达式内都评估为假。 A or B 就是这样一种表达方式。这个answer 解释得很清楚。
    【解决方案3】:
    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-17
      • 2012-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多