简体   繁体   English

Python-查找嵌套列表的总和

[英]Python - Find the sum of a Nested list

I'm having trouble of this recursive nested lists. 我有这个递归嵌套列表的麻烦。 The problem I have right now is the code work fine if the list isn't at the end of the list... I can't figure out what should I do to fix this. 我现在遇到的问题是,如果列表不在列表的末尾,则代码可以正常工作……我不知道该怎么办才能解决此问题。

def rsum(l):
    # Sum of all num in the list
    print l
    if isinstance(l[0], list):

        if len(l[0]) == 0:
            result = 0 + rsum(l[1:])

        else:
            sum_in_list = rsum(l[0])
            result = sum_in_list + rsum(l[1:])

    elif len(l) == 1:
        result = l[0]

    else:
        result = l[0] + rsum(l[1:])

    return result

So it work fine like this 这样就可以正常工作

l = [1, 2, [], 3, [2, 100], 4, [5], [], 2]
print rsum(l)
119

But if i do this 但是如果我这样做

l = [1, 2, [], 3, [2, 100], 4, [5], [], [2]]
IndexError: list index out of range

Any help or suggestion to point me in the right direction would be great 为我指明正确方向的任何帮助或建议都会很棒

If you call l[0] where there are no items in l , an IndexError will be raised. 如果在l中没有任何项的情况下调用l[0] ,则会引发IndexError

Catch it like this - 抓住这样-

else:
    try:
        result = l[0] + rsum(l[1:])
    except IndexError:
        result = 0

Or check for number of items in l 或检查l的项目数

else:
    if len(l) > 0: 
        result = l[0] + rsum(l[1:])
    else: 
        result = 0

Another version: 另一个版本:

>>> flatten = lambda *n: (e for a in n
...     for e in (flatten(*a) if isinstance(a, (tuple, list)) else (a,)))
>>> l = [1, 2, [], 3, [2, 100], 4, [5], [], 2]
>>> sum(flatten(l))
119

In Python 3, you can recursively use yield from to flatten arbitrary lists: 在Python 3中,您可以递归使用yield from来展平任意列表:

def flatten(L):
    for item in L:
        try:
            yield from flatten(item)
        except TypeError:
            yield item

>>> l = [1, 2, [], 3, [2, 100], 4, [5], [], 2]
>>> sum(flatten(l))
119

If you pass it an empty list, it will try to access l[0] and cause the error. 如果将其传递为空列表,它将尝试访问l[0]并导致错误。 But here's a simpler solution: 但这是一个更简单的解决方案:

def rsum(l):
    if isinstance(l, list):
        return sum(rsum(v) for v in l)
    else:
        return l

This should handle all cases. 这应该处理所有情况。

If you want a really concise version, you can use: 如果您想要一个非常简洁的版本,可以使用:

def rsum(l):
    return sum(map(rsum, l)) if isinstance(l, list) else l

Another take 另取

def rsum(L):
    return sum([rsum(i) for i in L]) if isinstance(L, list) else L

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM