在Python中对嵌套数据结构的浮点数进行四舍五入
我有一个程序,它处理的是嵌套的数据结构,这些结构里的数据类型通常是小数。比如:
x={'a':[1.05600000001,2.34581736481,[1.1111111112,9.999990111111]],...}
有没有什么简单的Python方法,可以打印这样的变量,同时把所有的小数都四舍五入到(比如)小数点后3位,而且不需要假设列表和字典的具体配置?比如:
{'a':[1.056,2.346,[1.111,10.000],...}
我在想类似于
pformat(x,round=3)
这样的东西,或者也许是
pformat(x,conversions={'float':lambda x: "%.3g" % x})
不过我觉得他们没有这种功能。当然,永久性地改变底层数据的值是不行的。
3 个回答
0
>>> 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里没有扁平化(flatten)的方法。因为我知道这个列表只嵌套了两层,所以我用了for循环
来处理。
1
假设你有一些浮点数的列表,这里有一个简单的方法:
>>> round = lambda l: [float('%.3g' % e) if type(e) is not list else round(e) for e in l]
>>> print({k: round(v) for k, v in x.items()})
{'a': [1.06, 2.35, [1.11, 10.0]]}
5
这个代码会递归地遍历字典、元组、列表等,格式化数字,同时保持其他内容不变。
import collections.abc
import numbers
def pformat(thing, formatfunc):
if isinstance(thing, dict):
return type(thing)((key, pformat(value, formatfunc)) for key, value in thing.items())
if isinstance(thing, collections.abc.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 Exception:
return thing
替换掉函数最后的三行代码。