Python中嵌套数据结构中的舍入小数

acr*_*bia 9 python printing rounding string-formatting

我有一个程序来处理嵌套数据结构,其中底层类型通常最终为小数.例如

x={'a':[1.05600000001,2.34581736481,[1.1111111112,9.999990111111]],...}
Run Code Online (Sandbox Code Playgroud)

是否有一种简单的pythonic方法来打印这样的变量,但将所有浮点数舍入到(例如)3dp并且不假设列表和字典的特定配置?例如

{'a':[1.056,2.346,[1.111,10.000],...}
Run Code Online (Sandbox Code Playgroud)

我想的是 pformat(x,round=3)或许也许

pformat(x,conversions={'float':lambda x: "%.3g" % x})
Run Code Online (Sandbox Code Playgroud)

除了我不认为他们有这种功能.永久舍入基础数据当然不是一种选择.

agf*_*agf 5

这将递归地递归dict,元组,列表等,格式化数字并保留其他内容。

import collections
import numbers
def pformat(thing, formatfunc):
    if isinstance(thing, dict):
        return type(thing)((key, pformat(value, formatfunc)) for key, value in thing.iteritems())
    if isinstance(thing, collections.Container):
        return type(thing)(pformat(value, formatfunc) for value in thing)
    if isinstance(thing, numbers.Number):
        return formatfunc(thing)
    return thing

def formatfloat(thing):
    return "%.3g" % float(thing)

x={'a':[1.05600000001,2.34581736481,[8.1111111112,9.999990111111]],
'b':[3.05600000001,4.34581736481,[5.1111111112,6.999990111111]]}

print pformat(x, formatfloat)
Run Code Online (Sandbox Code Playgroud)

如果您想尝试将所有内容都转换为浮点数,则可以执行

try:
    return formatfunc(thing)
except:
    return thing
Run Code Online (Sandbox Code Playgroud)

而不是函数的最后三行。