简体   繁体   中英

Printing formatted floats in nested tuple of mixed type

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM