简体   繁体   中英

Printing a tuple in Python with user-defined precision

Following Printing tuple with string formatting in Python , I'd like to print the following tuple:

tup = (0.0039024390243902443, 0.3902439024390244, -0.005853658536585366, -0.5853658536585366)

with only 5 digits of precision. How can I achieve this?

(I've tried print("%.5f" % (tup,)) but I get a TypeError: not all arguments converted during string formatting ).

You can print the floats with custom precision "like a tuple":

>>> tup = (0.0039024390243902443, 0.3902439024390244, -0.005853658536585366, -0.5853658536585366)
>>> print('(' + ', '.join(('%.5f' % f) for f in tup) + ')')
(0.00390, 0.39024, -0.00585, -0.58537)

尝试以下方法(列表理解)

['%.5f'% t for t in tup]

you can work on single item. Try this:

>>> tup = (0.0039024390243902443, 0.3902439024390244, -0.005853658536585366, -0.5853658536585366)
>>> for t in tup:
    print ("%.5f" %(t))


0.00390
0.39024
-0.00585
-0.58537

You can iterate over tuple like this, and than you can print result for python > 3

["{:.5f}".format(i) for i in tup] 

And for python 2.7

['%.5f'% t for t in tup]

Possible workaround:

tup = (0.0039024390243902443, 0.3902439024390244, -
       0.005853658536585366, -0.5853658536585366)

print [float("{0:.5f}".format(v)) for v in tup]

Most Pythonic way to achieve this is with map() and lambda() function.

>>> map(lambda x: "%.5f" % x, tup)
['0.00390', '0.39024', '-0.00585', '-0.58537']

I figured out another workaround using Numpy:

import numpy as np
np.set_printoptions(precision=5)
print(np.array(tup))

which yields the following output:

[ 0.0039   0.39024 -0.00585 -0.58537]

Here's a convenient function for python >3.6 to handle everything for you:

def tuple_float_to_str(t, precision=4, sep=', '):
    return '({})'.format(sep.join(f'{x:.{precision}f}' for x in t))

Usage:

>>> print(funcs.tuple_float_to_str((12.3456789, 8), precision=4))
(12.3457, 8.0000)

Try this:

class showlikethis(float):
    def __repr__(self):
        return "%0.5f" % self

tup = (0.0039024390243902443, 0.3902439024390244, -0.005853658536585366, -0.5853658536585366)
tup = map(showlikethis, tup)
print tup

You may like to re-quote your question, tuple dnt have precision.

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