且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在蟒蛇漂浮容易漂亮的打印?

更新时间:2022-10-21 23:31:15

更长期的解决方案是子类 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 $ c>如果你不想子类 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]