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

Time:01-04

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)

CodePudding user response:

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

CodePudding user response:

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)
  • Related