0

I am reading from an informix database on windows server via python and pyobdc.

Retrieving a row with decimal values I get something like this:

    [(Decimal("0.99"), ), (Decimal("0.0"), ), (Decimal("113.84"), ),.....]

It is no problem to get rid of the Word decimal but I cant figure out how to delete all the braces and " I dont need so that I can calculate the sum of this list.

What is the best way to do it in python?

1
  • You aren't "getting rid of words" because you presumably don't have a string; you have a data structure there. The string you show there is just a text representation of the data. Commented Aug 12, 2011 at 16:59

2 Answers 2

3

You can just calculate sum of Decimal objects, they have __sum__ method.

>>> from decimal import Decimal
>>> a = [(Decimal("0.99"), ), (Decimal("0.0"), ), (Decimal("113.84"), )]
>>> sum(i[0] for i in a) #Because they're in a tuple
Decimal('114.83')
Sign up to request clarification or add additional context in comments.

2 Comments

Strictly speaking, the from decimal import Decimal isn't necessary, since the Decimal objects have already been instantiated.
@Chinmay it's necessary to set up an example from scratch though :)
1

Your problem isn't that you have the Decimal("xyz") but that each value is in a tuple. So, you need to get the values out of the tuples so you can sum them.

a = [(Decimal("0.99"), ), (Decimal("0.0"), ), (Decimal("113.84"), ),.....]
b = sum(number[0] for number in a)

3 Comments

Does the Decimal() type support addition or does he first have to cast it to a float?
Decimal supports addition just fine.
@Brandon: they support addition. Casting to a float is a bad idea, as then you lose precision.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.