Printing formatted floats in nested tuple of mixed type
Asked Answered
W

1

6

I have a list of tuples where the entries in the tuples are mixed type (int, float, tuple) and want to print each element of the list on one line.

Example list:

 [('520',
     (0.26699505214910974, 9.530913611077067e-22, 1431,
     (0.21819421133984918, 0.31446394340528838), 11981481)),
 ('1219',
     (0.2775519783082116, 2.0226340976042765e-25, 1431,
     (0.22902629625165472, 0.32470159534237308), 14905481))]

I would like to print each tuple as a single line with the floats formatted to print to the ten-thousandth place:

 [('520', (0.2669, 9.5309e-22, 1431, (0.2181, 0.3144), 11981481)),
 ('1219', (0.2775, 2.0226e-25, 1431, (0.2290, 0.3247), 14905481))]

I was using pprint to get everything on one line

pprint(myList, depth=3, compact=True)
> ('1219', (0.2775519783082116, 2.0226340976042765e-25, 1431, (...), 14905481))]

but I wasn't sure how to properly format the floats in a pythonic manner. (There has to be a nicer way of doing it than looping through the list, looping through each tuple, checking if-float/if-int/if-tuple and converting all floats via "%6.4f" % x).

Weatherby answered 22/9, 2016 at 18:4 Comment(0)
B
3

This is not exactly what you need, but very close, and the code is pretty compact.

def truncateFloat(data):
    return tuple( ["{0:.4}".format(x) if isinstance(x,float) else (x if not isinstance(x,tuple) else truncateFloat(x)) for x in data])
pprint(truncateFloat(the_list))

For your example the result is

(('520', ('0.267', '9.531e-22', 1431, ('0.2182', '0.3145'), 11981481)),
 ('1219', ('0.2776', '2.023e-25', 1431, ('0.229', '0.3247'), 14905481)))

You can play with options of .format() to get what you want.

Burd answered 23/9, 2016 at 8:29 Comment(1)
Not as nice as I imagined (I feel like there should be some recursive print formatting function available), but get the jobs done. Thanks!Weatherby

© 2022 - 2024 — McMap. All rights reserved.