0

I've been very proud of myself of not having to ask any questions yet as I learn python. However, I can't seem to figure this one out.

I'm attempting to append data taken from json.dump, keep it until the loop is satisfied, and then add all of the numbers that were appended.

Below is a piece of my code (you can make fun of me, I'm sure it's horrendous). The purpose is: if text is equal to response text, parse the the json dictionary and enter a level. Once in the "orderFillTransaction" level, take the value of "pl" and append.

if 'orderFillTransaction' in json_data:
    print("Json_Data:", type(json_data))
    Closed_ID2 = json_data['orderFillTransaction']
    PL_List = (Closed_ID2['pl'])
    print("PL_List:", PL_List, type(PL_List))
    PL.append(PL_List)
    print("PL.append:", PL, type(PL))

Below is the output:

Json_Data: <class 'dict'>
PL_List: -0.1300 <class 'str'>
PL.append: ['-0.1300', '-0.1300'] <class 'list'>

The problem is, if I try to sum(), it errors out, if I float() I get some weird numbers; I just can't seem to figure out how to add each of the items together. If it matters, the numbers are usually negative.

Often time's I either get the errors below:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

or

ValueError: invalid literal for int () with base 10

I know it has something to do regarding a str inside a list instead of an int, however, I know there has to be some solution.

Any direction would be greatly appreciated. Thank you!

3 Answers3

1

Try:

>>> PL = ['-0.1300', '-0.1300']
>>> print(sum([float(i) for i in  PL]))

Output:

-0.26

I don't know what "weird" numbers you get using float but the above code works for me.

Sid
  • 2,174
  • 1
  • 13
  • 29
  • Thank you! Using the above code popped the cannot add a str error. I did get it to work though with the use of sum([eval(num) for num in PL]). The floating-point issue was causing the problems before if I'm not mistaken. – Charlie May 07 '20 at 12:15
0

if you change the line

PL.append(PL_List)

to

PL.append(float(PL_List))

(assuming PL is empty, or consists of other ints/floats at the onset), you should then be able to simply sum(PL).

The type error you referenced indicates that at some point a number was attempting to be added to a string. Converting each number to a float prior/during the list append should resolve that issue.

The second error can likely be averted by using float() instead of int(). Please see this link for more details.

Lastly, those weird numbers you mention sound as though they could be the result of python's representation of floats.

for example:

>>> numbers = [float(0.67), float(1.23), int(5), float("-1.2345")]
>>> print(numbers)
[0.67, 1.23, 5, -1.2345]
>>> sum(numbers)
5.665500000000001

There's a good explanation of float decimal precision here

Rexovas
  • 469
  • 2
  • 9
0

It seems like a floating-point issue that you're having. It's because the floating-point cannot be stored exactly on the computer -- we need to store some approximation of it. You can learn more about it here.

Possible fix: You can create a function to find the sum of your PL array that does some post rounding to the sum so that it does not look like a mess, however, make sure that it does not hurt any further calculations.

def sum_str_array(array):
    total = 0
    for item in array:
        total += float(item)
    return round(total, 5)   #rounded to 5 digits precision after summing all the elements

a = ['1.01', '-0.99', '-0.02']
print (sum_str_array(a))

This will give you 0.0 as answer after rounding which would be 1.734723475976807e-17 otherwise. Hope this helps.

youwez125
  • 33
  • 3