简体   繁体   中英

Summing a list of lists of lists?

I'm trying to sum a list of lists of lists in Python but I'm getting the wrong output. I want the number 36 as my answer but I'm getting the sum of each bracket.

>>> list = [[[1,2],[3,4]],[[5,6],[7,8]]]
>>> for xs in list[0::1]:
...     for x in xs[0::1]:
...         sum(x)
...
3
7
11
15

You can also use list comprehension like this -

>>> lst = [[[1,2],[3,4]],[[5,6],[7,8]]]
>>> sum([x for i in lst for y in i for x in y])
36

Or

>>> sum(sum(y) for x in lst for y in x)
36

Also, just FYI list is a bad name for a variable, since it overwrites the built-in list function.


If there are n nested lists (arbitrary number) I cannot think of a way to achieve the sum through list comprehension , but a simple recursive algorithm that would do the trick is -

>>> def sumOfList(element):
...     if isinstance(element, list):
...             return sum([sumOfList(x) for x in element])
...     elif isinstance(element, int):
...             return element
...
>>> sumOfList([[[1,2,3,4],[1,2,3,4]],[1,2,3]])
26

You could probably do this recursively, which would work for nested lists of arbitrary depth:

def add_all(l):
    try:
        return sum(add_all(i) for i in l)
    except TypeError:
        return l

print add_all([[[1,2],[3,4]],[[5,6],[7,8]]]) # 36

Here's a little more fancy way to do it:

You can use itertools.chain to remove one level of nesting from your list of lists:

>>> lst = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
>>> from itertools import chain
>>> list(chain(*lst)) # note: list != lst
[[1, 2], [3, 4], [5, 6], [7, 8]]

Now apply it twice and sum all items:

>>> sum(chain(*chain(*lst)))
36

Assign sublists sums to a variable:

total = 0
for x in list: # x is list of lists
  for y in x: # y is a list
     total = total + sum(y)
print total

You can create a recursive function like this:

def rsum(lst):
  if type(lst) != list:
    return lst
  if len(lst)==1:
    return rsum(lst[0])
  return rsum(lst.pop(0))+rsum(lst)

The difference is that it works for a nested list of any depth

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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