如何在 Python 中舍入 yaml.dump 的数字输出?

Ole*_*kov 4 python precision yaml rounding python-3.x

有没有一种干净的方法来控制 的数字舍入输出yaml.dump?例如,我有一个具有不同复杂性变量的类,其中一些是双精度数字,我想四舍五入为第四位数字。该yaml输出仅供显示;它不会被加载(即yaml.load不会被使用)。

作为一个简单的例子,考虑A下面的类:

import yaml
class A:
    def __init__(self):
        self.a = 1/7
        self.b = 'some text'
        self.c = [1/11, 1/13, 1/17, 'some more text']

    def __repr__(self):
        return yaml.dump(self)

A()
Run Code Online (Sandbox Code Playgroud)

带输出

!!python/object:__main__.A
a: 0.14285714285714285
b: some text
c: [0.09090909090909091, 0.07692307692307693, 0.058823529411764705, some more text]
Run Code Online (Sandbox Code Playgroud)

和期望的输出:

!!python/object:__main__.A
a: 0.1429
b: some text
c: [0.0909, 0.0769, 0.0588, some more text]
Run Code Online (Sandbox Code Playgroud)

yaml.representative我想这可以通过某种干净的方式来完成。我想避免使用字符串输出的舍,因为实际的类结构可能更复杂(递归等)

jfs*_*jfs 6

您可以手动舍入它:

#!/usr/bin/env python
import yaml

def float_representer(dumper, value):
    text = '{0:.4f}'.format(value)
    return dumper.represent_scalar(u'tag:yaml.org,2002:float', text)
yaml.add_representer(float, float_representer)

print(yaml.safe_dump([1 / 11, 1 / 13, 1 / 17, 'some more text']))
print(yaml.dump([1 / 11, 1 / 13, 1 / 17, 'some more text']))
Run Code Online (Sandbox Code Playgroud)

输出

[0.09090909090909091, 0.07692307692307693, 0.058823529411764705, some more text]

[0.0909, 0.0769, 0.0588, some more text]
Run Code Online (Sandbox Code Playgroud)

您可能需要为极端情况添加更多代码,请参阅represent_float()@memoselyk建议