Sum values of each tuples enclosed of two lists. The problem is that they add together, but don't sum

99 Views Asked by At

I would sum the values of each tuple enclosed in two lists. The output i would like to get is: 125, 200.0, 100.0.

The problem is that they don't sum, but they add like this [(87.5, 37.5), (125.0, 75.0), (50.0, 50.0)]. I need first and second to stay the same as mine, without changing any parentheses. I've searched for many similar answers on stackoverflow, but haven't found any answers for my case.

How can i edit calc and fix it? Thank you!

Code:

first = [(87.5,), (125.0,), (50.0,)]
second = [(37.5,), (75.0,), (50.0,)]

calc = [x + y for x, y in zip(first, second)]
print(calc)
3

There are 3 best solutions below

0
On BEST ANSWER

The problem is that you are trying to add the tuples (if you do type(x) or type(y) you see that those are tuple values and not the specific floats that you have) if you want to add the values inside of the tuples then you have to access the elements you can do it like so:

    first = [(87.5,), (125.0,), (50.0,)]
    second = [(37.5,), (75.0,), (50.0,)]
    
    calc = [x[0] + y[0] for x, y in zip(first, second)] # accessing the first element of x and y -- as there is only 1 element in each of the tuples. 
    # if you had more elements in each tuple you could do the following: calc = [sum(x) + sum(y) for x, y in zip(first, second)]
    print(calc)
    print(first, second)
1
On

All the values in your two lists are wrapped in tuples, so you should unpack them accordingly:

calc = [x + y for [x], [y] in zip(first, second)]
2
On

If installed and anyway part of your code, there is a way to use numpy:

import numpy as np

first = [(87.5,), (125.0,), (50.0,)]
second = [(37.5,), (75.0,), (50.0,)]

(np.array(first) + np.array(second)).T.tolist()[0]

Output

[125.0, 200.0, 100.0]