问题描述
好的,我想使用repr()打印出一堆列表和嵌套数组的文本版本.
Okay, I want to use repr() to print out a text version of a bunch of lists and nested arrays.
但是我希望数字只保留小数点后4位,而不是:42.7635745114,而是32.7635.
But I want the numbers to have only 4 decimal places not: 42.7635745114 but 32.7635.
我想使用repr(),因为它具有很好的处理嵌套数组的能力.编写自己的打印循环是一种没有吸引力的选择.
I'd like to use repr() because of its nice ability to handle nested arrays. Writing my own print loop is an unattractive option.
当然有某种方法可以使repr重载吗?我看到有一个repr和reprlib模块,但是示例确实很少,就像不存在一样.
Surely there is some way to overload repr to do this? I see there is a repr and reprlib modules but examples are really scarce, like nonexistent.
推荐答案
不,没有办法使repr()
重载.浮点数的格式在C源代码中进行了硬编码.
No, there is no way to overload repr()
. The format for floats is hardcoded in the C source code.
float_repr()
函数调用一个'r'
格式化程序的辅助函数,最终会调用实用程序将格式硬编码为的功能,最终归结为format(float, '.16g')
.
The float_repr()
function calls a helper function with the 'r'
formatter, which eventually calls a utility function that hardcodes the format to what comes down to format(float, '.16g')
.
您可以继承float
的子类,但仅这样做来表示值(尤其是在较大的结构中)就太过分了.这是repr
(Python 3中的reprlib
)出现的地方;该库旨在打印任意数据结构的有用表示形式,并让您着迷于在该结构中打印特定类型.
You could subclass float
, but to only do that for representing values (especially in a larger structure) is overkill. This is where repr
(reprlib
in Python 3) comes in; that library is designed to print useful representations of arbitrary data structures, and letting you hook into printing specific types in that structure.
您可以通过子类化 repr.Repr()
来使用repr
模块. ,提供用于处理浮点的repr_float()
方法:
You could use the repr
module by subclassing repr.Repr()
, providing a repr_float()
method to handle floats:
try: # Python 3
import reprlib
except ImportError: # Python 2
import repr as reprlib
class FloatRepr(reprlib.Repr):
def repr_float(self, value, level):
return format(value, '.4f')
print(FloatRepr().repr(object_to_represent))
演示:
>>> import random
>>> import reprlib
>>> class FloatRepr(reprlib.Repr):
... def repr_float(self, value, level):
... return format(value, '.4f')
...
>>> print(FloatRepr().repr([random.random() for _ in range(5)]))
[0.5613, 0.9042, 0.3891, 0.7396, 0.0140]
您可能想在子类上设置max*
属性,以影响每种容器类型打印多少个值.
You may want to set the max*
attributes on your subclass to influence how many values are printed per container type.
这篇关于Python更改REPR浮动数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!