Easy pretty printing of floats in python?

2020-01-23 17:15发布

I have a list of floats. If I simply print it, it shows up like this:

[9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006]

I could use print "%.2f", which would require a for loop to traverse the list, but then it wouldn't work for more complex data structures. I'd like something like (I'm completely making this up)

>>> import print_options
>>> print_options.set_float_precision(2)
>>> print [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006]
[9.0, 0.05, 0.03, 0.01, 0.06, 0.08]

18条回答
Explosion°爆炸
2楼-- · 2020-01-23 17:15

List comps are your friend.

print ", ".join("%.2f" % f for f in list_o_numbers)

Try it:

>>> nums = [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999]
>>> print ", ".join("%.2f" % f for f in nums)
9.00, 0.05, 0.03, 0.01
查看更多
【Aperson】
3楼-- · 2020-01-23 17:17

Note that you can also multiply a string like "%.2f" (example: "%.2f "*10).

>>> print "%.2f "*len(yourlist) % tuple(yourlist)
2.00 33.00 4.42 0.31 
查看更多
Evening l夕情丶
4楼-- · 2020-01-23 17:18

The code below works nice to me.

list = map (lambda x: float('%0.2f' % x), list)
查看更多
一夜七次
5楼-- · 2020-01-23 17:20

You can do:

a = [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006]
print ["%0.2f" % i for i in a]
查看更多
虎瘦雄心在
6楼-- · 2020-01-23 17:20

I just ran into this problem while trying to use pprint to output a list of tuples of floats. Nested comprehensions might be a bad idea, but here's what I did:

tups = [
        (12.0, 9.75, 23.54),
        (12.5, 2.6, 13.85),
        (14.77, 3.56, 23.23),
        (12.0, 5.5, 23.5)
       ]
pprint([['{0:0.02f}'.format(num) for num in tup] for tup in tups])

I used generator expressions at first, but pprint just repred the generator...

查看更多
\"骚年 ilove
7楼-- · 2020-01-23 17:23

It's an old question but I'd add something potentially useful:

I know you wrote your example in raw Python lists, but if you decide to use numpy arrays instead (which would be perfectly legit in your example, because you seem to be dealing with arrays of numbers), there is (almost exactly) this command you said you made up:

import numpy as np
np.set_printoptions(precision=2)

Or even better in your case if you still want to see all decimals of really precise numbers, but get rid of trailing zeros for example, use the formatting string %g:

np.set_printoptions(formatter={"float_kind": lambda x: "%g" % x})

For just printing once and not changing global behavior, use np.array2string with the same arguments as above.

查看更多
登录 后发表回答