在蟒蛇漂浮容易漂亮的打印? [英] Easy pretty printing of floats in python?
问题描述
print
,它会显示如下: [ 9.0,0.052999999999999999,0.032575399999999997,0.010892799999999999,0.055702500000000002,0.079330300000000006]
我可以使用打印%.2f
,这要求循环遍历列表,但是这对于更复杂的数据结构。
我喜欢这样的东西(我完全是这样做的)
>>> import print_options
>>> print_options.set_float_precision(2)
>>>打印[9.0,0.052999999999999999,0.032575399999999997,0.010892799999999999,0.055702500000000002,0.079330300000000006]
[9.0,0.05,0.03,0.01,0.06,0.08]
更长期的解决方案是子类 float
:
>>> (漂浮):
def __repr __(self):
return%0.2f%self
>>> x
[1.290192,3.0002,22.119199999999999,3.4110999999999998]
>>> x = map(prettyfloat,x)
>>> x
[1.29,3.00,22.12,3.41]
>>> y = x [2]
>>> y
22.12
子类化的问题 float
是它破坏了显式查找变量类型的代码。但据我所知,这是唯一的问题。并且一个简单的 x = map(float,x)
将取消转换为 prettyfloat
。
悲惨的是,你不能只是因为
float 如果你不想子类 float
,但是不介意定义一个函数, map(f,x)
比 [f(n)for n in x]简洁得多
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]
解决方案 A more permanent solution is to subclass float
:
>>> class prettyfloat(float):
def __repr__(self):
return "%0.2f" % self
>>> x
[1.290192, 3.0002, 22.119199999999999, 3.4110999999999998]
>>> x = map(prettyfloat, x)
>>> x
[1.29, 3.00, 22.12, 3.41]
>>> y = x[2]
>>> y
22.12
The problem with subclassing float
is that it breaks code that's explicitly looking for a variable's type. But so far as I can tell, that's the only problem with it. And a simple x = map(float, x)
undoes the conversion to prettyfloat
.
Tragically, you can't just monkey-patch float.__repr__
, because float
's immutable.
If you don't want to subclass float
, but don't mind defining a function, map(f, x)
is a lot more concise than [f(n) for n in x]
这篇关于在蟒蛇漂浮容易漂亮的打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!