Printing formatted floats in nested tuple of mixed type
<p>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. </p>

<p>Example list:</p>

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

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

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

<p>I was using <code>pprint</code> to get everything on one line</p>

<pre><code>pprint(myList, depth=3, compact=True)
&gt; ('1219', (0.2775519783082116, 2.0226340976042765e-25, 1431, (...), 14905481))]
</code></pre>

<p>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 <code>"%6.4f" % x</code>). </p>

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

<pre><code>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))
</code></pre>

<p>For your example the result is</p>

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

<p>You can play with options of <code>.format()</code> to get what you want.</p>

python pretty-print pprint