3

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)
pmqs
  • 3,066
  • 2
  • 13
  • 22
  • 2
    There are only parentheses because you have tuples, not numbers, in your list. You don't want to add `x` and `y`; you want to add the *contents* of `x` and `y` in an element-wise fashion. – chepner Jan 04 '23 at 01:38

3 Answers3

3

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)
Andrew Ryan
  • 1,489
  • 3
  • 15
  • 21
3

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)]
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • 1
    Your answer and also the other user's are both great. I'm in trouble because I would like to accept the answer of both. Please excuse me if I accept the other user's answer: he was the first to answer and also he needs to score. I really appreciated your answer. I still voted for you. Thank you, thank you very much –  Jan 06 '23 at 08:26
0

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]

Andreas
  • 159
  • 1
  • 7
  • 1
    What is the difference between using numpy and using normal python code like in the above two answers? I upvoted your answer. Thank you –  Jan 05 '23 at 00:25
  • 1
    To do justice to the KISS concept, you should keep the effort as small as necessary to solve the problem. For small amounts of data, the solutions already mentioned are good, but for larger amounts of data (or if numpy is part of the project anyway), the numpy variant is preferable. – Andreas Jan 05 '23 at 08:49