user20812299
user20812299

Reputation:

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

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)

Upvotes: 3

Views: 97

Answers (3)

Andreas
Andreas

Reputation: 159

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]

Upvotes: 0

Andrew Ryan
Andrew Ryan

Reputation: 1611

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)

Upvotes: 3

blhsing
blhsing

Reputation: 106891

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)]

Upvotes: 3

Related Questions