简体   繁体   English

以用户定义的精度在Python中打印元组

[英]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: 在Python中使用字符串格式打印元组之后,我想打印以下元组:

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

with only 5 digits of precision. 仅有5位数的精度。 How can I achieve this? 我该如何实现?

(I've tried print("%.5f" % (tup,)) but I get a TypeError: not all arguments converted during string formatting ). (我尝试过print("%.5f" % (tup,))但出现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 您可以像这样遍历元组,然后可以打印python> 3的结果

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

And for python 2.7 对于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. 实现此目标的大多数Python方法是使用map()lambda()函数。

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

I figured out another workaround using Numpy: 我想出了另一个使用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: 这是python> 3.6的一个便捷函数,可以为您处理所有事情:

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. 您可能想重新引用您的问题,元组dnt具有精度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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