Yang Liu
Yang Liu

Reputation: 45

Sum Lists' value with corresponding index value in Python

I used a big list to represent a lot of needed values, which is really complicated to me.

For example:

    [[[a,b,c],[d,e,f]],
     [[g,h,i],[j,k,l]],
     [[o,p,u],[r,s,t]]]

And I want to combine the three major indices and their corresponding value together. I don't mean to concatenate.

For example the result would be:

    [[(a+g+o),(b+h+p),(c+i+u)],[(d+j+r),(e+k+s),(f+l+t)]]

Can someone help me how to accomplish this result? Thanks!

Upvotes: 4

Views: 7212

Answers (2)

John1024
John1024

Reputation: 113814

This kind of thing really calls for numpy:

>>> a = [[[ 1, 2, 3], [ 4, 5, 6]],
        [ [ 7, 8, 9], [10,11,12]],
        [ [13,14,15], [16,17,18]]]
>>> import numpy
>>> numpy.array(a).sum(axis=0)
array([[21, 24, 27],
       [30, 33, 36]])

The array function converts the data to a numpy array. Such arrays can be manipulated quite powerfully. In your case, you want to sum along the first (that is, zeroth) axis. This is done by invoking sum(axis=0).

Upvotes: 2

shaktimaan
shaktimaan

Reputation: 12092

Here you go. Since you said adding, I am assuming a, b, c, etc are all integers.

>> a = [[[1,2,3],[4,5,6]],
... [[7,8, 9],[10, 11, 12]],
... [[16, 17, 18],[13, 14, 15]]]

>>> temp_list = list(zip(*b) for b in zip(*a))
>>> result = [[sum(list(a)) for a in b] for b in temp_list]
>>> result
[[24, 27, 30], [27, 30, 33]]

An intimidating one-liner would be:

[[sum(list(a)) for a in b] for b in list(zip(*b) for b in zip(*a))]

Let's step through the code line by line.

  1. zip(*a) will give you:

    >>> zip(*a)
    [([1, 2, 3], [7, 8, 9], [16, 17, 18]), ([4, 5, 6], [10, 11, 12], [13, 14, 15])]
    

    It combined the first inner most lists of the sublists.

  2. We need to do another zip on this. list(zip(*b) for b in zip(*a)) will give us:

    [[(1, 7, 16), (2, 8, 17), (3, 9, 18)], [(4, 10, 13), (5, 11, 14), (6, 12, 15)]]
    
  3. Now we just need to sum these and create a list of lists. So we do:

    [[sum(list(a)) for a in b] for b in temp_list]
    

If the lists are going to be large, I would suggest using itertools' version of zip called izip(). But izip() returns a generator and not a list. So, you would need to convert it to lists.

Upvotes: 3

Related Questions