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

Python中嵌套数据结构中的舍入小数,python,printing,string-formatting,rounding,Python,Printing,String Formatting,Rounding,我有一个处理嵌套数据结构的程序,其中底层类型通常以十进制结束。e、 g x={'a':[1.05600000001,2.34581736481,[1.1111111112,9.999990111111]],...} 是否有一种简单的python方法来打印这样一个变量,但将所有浮点值舍入到(比如)3dp,而不采用列表和字典的特定配置?e、 g {'a':[1.056,2.346,[1.111,10.000],...} 我在想 pformat(x,round=3)或者 pformat(x,con

我有一个处理嵌套数据结构的程序,其中底层类型通常以十进制结束。e、 g

x={'a':[1.05600000001,2.34581736481,[1.1111111112,9.999990111111]],...}
是否有一种简单的python方法来打印这样一个变量,但将所有浮点值舍入到(比如)3dp,而不采用列表和字典的特定配置?e、 g

{'a':[1.056,2.346,[1.111,10.000],...}
我在想
pformat(x,round=3)
或者

pformat(x,conversions={'float':lambda x: "%.3g" % x})
除了我不认为他们有这种功能。当然,永久性地舍入基础数据不是一种选择

>>> b = []
>>> x={'a':[1.05600000001,2.34581736481,[1.1111111112,9.999990111111]]}
>>> for i in x.get('a'):
        if type(i) == type([]):
            for y in i:
                print("%0.3f"%(float(y)))
        else:
            print("%0.3f"%(float(i)))


    1.056
    2.346
    1.111
    10.000

这里的问题是我们在python中没有flatte方法,因为我知道它只是我在循环中使用的两级列表嵌套

这将递归地降低dicts、tuple、list等。格式化数字,而不处理其他内容

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)
如果您想尝试将所有内容转换为浮点,您可以这样做

try:
    return formatfunc(thing)
except:
    return thing

而不是函数的最后三行。

一种简单的方法,假设您有浮动列表:

>>> round = lambda l: [float('%.3g' % e) if type(e) != list else round(e) for e in l]
>>> print {k:round(v) for k,v in x.iteritems()}
{'a': [1.06, 2.35, [1.11, 10.0]]}

运行像[floor(x*1000)/1000.0 for a中的x]这样的循环怎么样?这只适用于数字列表。lambda通过名称来引用自身是错误的,这就是命名函数或y-combinator的用途:)。他还说,类型“通常以十进制结束”,因此我认为有时它们不能
float
使用。我将把它作为练习留给读者,让他们将
round=lambda l:…
def round(l):return…
:d交换
round=lambda l:…
:但是y-combinator非常棒,在Python中使用它是没有理由的!尝试使此函数正常工作-引发错误:TypeError:pformat()缺少1个必需的位置参数:“formatfunc”此代码通过在pformat(value,formatfunc)上添加参数来修复,感谢@Xmoů修复此问题!