Skip to content Skip to sidebar Skip to footer

Rounding Decimals In Nested Data Structures In Python

I have a program which deals with nested data structures where the underlying type usually ends up being a decimal. e.g. x={'a':[1.05600000001,2.34581736481,[1.1111111112,9.99999

Solution 1:

This will recursively descend dicts, tuples, lists, etc. formatting numbers and leaving other stuff alone.

import collections
import numbers
defpformat(thing, formatfunc):
    ifisinstance(thing, dict):
        returntype(thing)((key, pformat(value, formatfunc)) for key, value in thing.iteritems())
    ifisinstance(thing, collections.Container):
        returntype(thing)(pformat(value, formatfunc) for value in thing)
    ifisinstance(thing, numbers.Number):
        return formatfunc(thing)
    return thing

defformatfloat(thing):
    return"%.3g" % float(thing)

x={'a':[1.05600000001,2.34581736481,[8.1111111112,9.999990111111]],
'b':[3.05600000001,4.34581736481,[5.1111111112,6.999990111111]]}

print pformat(x, formatfloat)

If you want to try and convert everything to a float, you can do

try:
    return formatfunc(thing)
except:
    return thing

instead of the last three lines of the function.

Solution 2:

A simple approach assuming you have lists of floats:

>>>round = lambda l: [float('%.3g' % e) iftype(e) != listelseround(e) for e in l]>>>print {k:round(v) for k,v in x.iteritems()}
{'a': [1.06, 2.35, [1.11, 10.0]]}

Solution 3:

>>> b = []
>>> x={'a':[1.05600000001,2.34581736481,[1.1111111112,9.999990111111]]}
>>> for i in x.get('a'):
        iftype(i) == type([]):
            for y in i:
                print("%0.3f"%(float(y)))
        else:
            print("%0.3f"%(float(i)))


    1.0562.3461.11110.000

The problem Here is we don't have flatten method in python, since I know it is only 2 level list nesting I have used for loop.

Post a Comment for "Rounding Decimals In Nested Data Structures In Python"