轻松漂亮地打印花车? [英] Easy pretty printing of floats?
问题描述
我有一个浮点数列表.如果我只是print
,它会显示如下:
[9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.05570250000000000007]032575399999999997
我可以使用 print "%.2f"
,这需要一个 for
循环来遍历列表,但它不适用于更复杂的数据结构.我想要类似的东西(我完全是编造出来的)
这是一个老问题,但我会添加一些可能有用的内容:
我知道您在原始 Python 列表中编写了您的示例,但是如果您决定使用 numpy
数组代替(这在您的示例中是完全合法的,因为您似乎正在处理数字数组),有(几乎完全是)你说的这个命令是你编造的:
将 numpy 导入为 npnp.set_printoptions(precision=2)
如果您仍然想查看真正精确数字的所有小数,但例如去掉尾随零,或者在您的情况下甚至更好,请使用格式化字符串 %g
:
np.set_printoptions(formatter={"float_kind": lambda x: "%g" % x})
为了只打印一次而不改变全局行为,使用 np.array2string
和上面相同的参数.
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]
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.
这篇关于轻松漂亮地打印花车?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!