[英]Round floats in a nested dictionary recursively
我正在尝试在具有其他值的嵌套字典中舍入浮点值。 我看着这个线程- 在Python的嵌套数据结构中舍入小数
尝试实现如下功能:
import collections
import numbers
def formatfloat(x):
return "%.3g" % float(x)
def pformat(dictionary, function):
if isinstance(dictionary, dict):
return type(dictionary)((key, pformat(value)) for key, value in dictionary.items())
if isinstance(dictionary, collections.Container):
return type(dictionary)(pformat(value) for value in dictionary)
if isinstance(dictionary, numbers.Number):
return formatfunc(dictionary)
return dictionary
x={'a':[1.05600000001,2.34581736481,[8.1111111112,9.999990111111]],
'b':[3.05600000001,4.34581736481,[5.1111111112,6.999990111111]]}
pformat(x, formatfloat)
我收到此错误:
TypeError: pformat() missing 1 required positional argument: 'function'
答案被标记为正确,所以我想知道是否需要更改任何内容。 这正是我要为字典实现的内容。 任何帮助表示赞赏!
这里只是语法错误。
您pformat
在内部调用函数pformat
而不需要任何参数。 您只传递值而不传递函数
return type(dictionary)((key, pformat(value)) for key, value in dictionary.items())
在最后的if
语句中,您调用未实现的函数formatfunc
。 可能是拼写错误,您需要调用formatfloat
函数。
如果解决此问题,结果:
{'a': ['1.06', '2.35', ['8.11', '10']], 'b': ['3.06', '4.35', ['5.11', '7']]}
您需要在pformat之后添加一个参数:
之前
pformat(value))
后:
pformat(value, function))
然后更改错字错误:formatfunc起作用
这是工作代码:
import collections
import numbers
def formatfloat(x):
return "%.3g" % float(x)
def pformat(dictionary, function):
if isinstance(dictionary, dict):
return type(dictionary)((key, pformat(value, function)) for key, value in dictionary.items())
if isinstance(dictionary, collections.Container):
return type(dictionary)(pformat(value, function) for value in dictionary)
if isinstance(dictionary, numbers.Number):
return function(dictionary)
return dictionary
x={'a':[1.05600000001,2.34581736481,[8.1111111112,9.999990111111]],
'b':[3.05600000001,4.34581736481,[5.1111111112,6.999990111111]]}
pformat(x, formatfloat)
结果:
{'a': ['1.06', '2.35', ['8.11', '10']], 'b': ['3.06', '4.35', ['5.11', '7']]}
我写的有点不同:
x={'a':[1.05600000001,2.34581736481,[8.1111111112,9.999990111111]],
'b':[3.05600000001,4.34581736481,[5.1111111112,6.999990111111]]}
def recursive_rounding(keys, values):
to_return = {}
for key, value in zip(keys, values):
print key, value
if isinstance(value, dict):
rounded_value = recursive_rounding(value.keys(), value.values())
elif isinstance(value, (tuple, list)):
rounded_value = [round_by_type(x) for x in value]
else:
rounded_value = round_by_type(value)
print key, value
to_return[round_by_type(key)] = rounded_value
return to_return
def round_by_type(to_round):
if isinstance(to_round, (int, float)):
return round(to_round, 2)
elif isinstance(to_round, (list, tuple)):
return [round_by_type(x) for x in to_round]
return to_round
recursive_rounding(x.keys(), x.values())
我超级快地编写了它,可以对其进行一些清理和改进,但是只是为了向您展示如何从不同的角度来处理它。
输出是:
# Result: {'a': [1.06, 2.35, [8.11, 10.0]], 'b': [3.06, 4.35, [5.11, 7.0]]} #
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.