在 Python 中的嵌套数据结构中舍入小数 [英] Rounding decimals in nested data structures in Python

查看:38
本文介绍了在 Python 中的嵌套数据结构中舍入小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个处理嵌套数据结构的程序,其中底层类型通常以十进制结尾.例如

I have a program which deals with nested data structures where the underlying type usually ends up being a decimal. e.g.

x={'a':[1.05600000001,2.34581736481,[1.1111111112,9.999990111111]],...}

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

Is there a simple pythonic way to print such a variable but rounding all floats to (say) 3dp and not assuming a particular configuration of lists and dictionaries? e.g.

{'a':[1.056,2.346,[1.111,10.000],...}

我在想类似的事情pformat(x,round=3) 或者可能

I'm thinking something like pformat(x,round=3) or maybe

pformat(x,conversions={'float':lambda x: "%.3g" % x})

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

except I don't think they have this kind of functionality. Permanently rounding the underlying data is of course not an option.

推荐答案

这将递归下降字典、元组、列表等,格式化数字并保留其他内容.

This will recursively descend dicts, tuples, lists, etc. formatting numbers and leaving other stuff alone.

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)

如果您想尝试将所有内容转换为浮点数,您可以这样做

If you want to try and convert everything to a float, you can do

try:
    return formatfunc(thing)
except:
    return thing

而不是函数的最后三行.

instead of the last three lines of the function.

这篇关于在 Python 中的嵌套数据结构中舍入小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆