>>>import json
>>>d = { ‘a‘: 0.333333333, ‘b‘: 0.445444444, ‘c‘: 0.293 }
>>>json.dumps(d)
得到
‘{"a": 0.333333333, "c": 0.293, "b": 0.445444444}‘
而我们期望得到
‘{"a": 0.33, "c": 0.29, "b": 0.45}‘
以下是解决办法
http://stackoverflow.com/questions/1447287/format-floats-with-standard-json-module
import json def pretty_floats(obj): if isinstance(obj, float): return round(obj, 3) elif isinstance(obj, dict): return dict((k, pretty_floats(v)) for k, v in obj.items()) elif isinstance(obj, (list, tuple)): return map(pretty_floats, obj) return obj d = { ‘a‘: 0.333333333, ‘b‘: 0.445444444, ‘c‘: 0.293 } print json.dumps(pretty_floats(d))
时间: 2024-10-23 19:02:46