-4

So, I have a list that looks something like this

[[[1, 2], [3, 4], [5, 6]],
 [[7, 8], [9, 10], [11, 12]],
 [[13, 14], [15, 16], [17, 18]],
 [[19, 20], [21, 22], [23, 24]]]

And I want it to look like this

[[3, 7, 11],
 [15, 19, 23],
 [27, 31, 35],
 [39, 43, 27]]

that is 3 = sum([1, 2]), 7 = sum([3, 4]), ....

I have tried nesting for loops but I haven't found anything that got the desired result, does anyone know how I could do this?

ruohola
  • 19,113
  • 6
  • 51
  • 82
Robert
  • 11

3 Answers3

2

This will do the job quite nicely and imo is more readable than list comprehensions.

lists = [[[1, 2], [3, 4], [5, 6]],
        [[7, 8], [9, 10], [11, 12]],
        [[13, 14], [15, 16], [17, 18]],
        [[19, 20], [21, 22], [23, 24]]]

new_lists = []
for nested in lists:
    new_ls = []
    for ls in nested:
        new_ls.append(sum(ls))
    new_lists.append(new_ls)


>>> new_lists
[[3, 7, 11], [15, 19, 23], [27, 31, 35], [39, 43, 47]]
ruohola
  • 19,113
  • 6
  • 51
  • 82
2

You could also use list comprehensions:

[[sum(x) for x in triple] for triple in lists]

In the above list comprehension, triple will be your list of three doubles so the first for loop will be covering these. x will then be each list of doubles, inside of the triple so we are summing it, while keeping it inside the original triple by using this bracket around:

[sum(x) for x in triple]

output:

[[3, 7, 11], [15, 19, 23], [27, 31, 35], [39, 43, 47]]
d_kennetz
  • 4,918
  • 5
  • 20
  • 44
0

If you are happy to use a 3rd party library, you can use NumPy and sum along a single dimension:

import numpy as np

A = np.array([[[1, 2], [3, 4], [5, 6]],
              [[7, 8], [9, 10], [11, 12]],
              [[13, 14], [15, 16], [17, 18]],
              [[19, 20], [21, 22], [23, 24]]])

res = A.sum(2)

Result:

array([[ 3,  7, 11],
       [15, 19, 23],
       [27, 31, 35],
       [39, 43, 47]])

See also: What are the advantages of NumPy over regular Python lists?

jpp
  • 147,904
  • 31
  • 244
  • 302