How to sum list values in tuples?

5

I have for example a list with tuples, and within these tuples I have 2 lists, where only the second list of each tuple varies: x= [(y, [1, 2]), (y, [3,4]), (y, [5, 6])]

How do I add the first values of lists within the tuples, like this:

1+3+5 = 9
2+4+6 = 12
Ficando: [9, 12]

Note: I just want to add the values of the second lists of each tuple.

    
asked by anonymous 17.04.2015 / 16:13

3 answers

3

You can do something like:

x= [('y', [1, 2]), ('y', [3,4]), ('y', [5, 6])]
soma = [0]*2
for t in x:
    soma[0] += t[1][0]
    soma[1] += t[1][1]
print soma

This will return:

[9,12]

Edit

To fit the answer to your comment, one possibility is to do the following:

x = [('y', [1, 2]), ('y', [3,4]), ('y', [5, 6])]
soma = []
for t in x:
    for i in xrange(len(t[1])):
        if i == len(soma):
            soma.append(0)
        soma[i] += t[1][i]
print soma
    
17.04.2015 / 16:20
4

In itertools there is a variant of zip which, when combining lists of different sizes, does not discard the extra elements, but uses None for its values:

>>> teste = [[1,2,3],[4,5],[6,7,8,9]]
>>> list(izip_longest(*teste))
[(1, 4, 6), (2, 5, 7), (3, None, 8), (None, None, 9)]

Credit

Or, if you specified a default value via fillvalue , this value is used (good for assigning zero and not interfering with sum):

>>> teste = [[1,2,3],[4,5],[6,7,8,9]]
>>> list(izip_longest(*teste, fillvalue=0))
[(1, 4, 6), (2, 5, 7), (3, 0, 8), (0, 0, 9)]

So you can use some list comprehensions to get the list of sums in a single command:

>>> x= [(y, [1, 2, 3]), (y, [4, 5]), (y, [6, 7, 8, 9])]
>>> somas = [sum(numeros) for numeros in
...   izip_longest(*[segundo for primeiro,segundo in x], fillvalue=0)
... ]
>>> somas
[11, 14, 11, 9]
    
17.04.2015 / 16:49
0

One line solution, without using import nor for :

>>> sum([b[0] for a, b in x]), sum([b[1] for a,b in x])
(9, 12)

Version that returns a list:

>>> [sum([b[0] for a, b in x]), sum([b[1] for a,b in x])]
[9, 12]
    
17.04.2015 / 20:47