如何在 Python 中舍入 yaml.dump 的数字输出?
How to round numeric output from yaml.dump, in Python?
是否有一种干净的方法来控制 yaml.dump
的数字舍入输出?例如,我有一个 class 具有不同的复杂性变量,其中一些是双精度数字我想四舍五入说第 4 位。此 yaml
输出仅供显示;它不会被加载(即 yaml.load
不会被使用)。
作为一个天真的例子,请考虑下面的 class 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()
输出
!!python/object:__main__.A
a: 0.14285714285714285
b: some text
c: [0.09090909090909091, 0.07692307692307693, 0.058823529411764705, some more text]
和所需的输出:
!!python/object:__main__.A
a: 0.1429
b: some text
c: [0.0909, 0.0769, 0.0588, some more text]
我想这可以用 yaml.representative
以某种干净的方式完成。
我想避免使用字符串 output 的舍入,因为实际的 class 结构可能更复杂(递归等)
为浮点数创建您自己的 repesenter,根据需要格式化浮点数,并用 yaml.add_representer(float, my_custom_repesenter)
替换现有的表示器。
Here 你可以找到浮点数的默认代表。您可以将该代码作为起点,仅更改值不是 [+-].inf
或 .nan
的路径,然后将 value
调整为您想要的精度。
您可以手动四舍五入:
#!/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']))
输出
[0.09090909090909091, 0.07692307692307693, 0.058823529411764705, some more text]
[0.0909, 0.0769, 0.0588, some more text]
您可能需要为极端情况添加更多代码,请参阅 represent_float()
as 。
是否有一种干净的方法来控制 yaml.dump
的数字舍入输出?例如,我有一个 class 具有不同的复杂性变量,其中一些是双精度数字我想四舍五入说第 4 位。此 yaml
输出仅供显示;它不会被加载(即 yaml.load
不会被使用)。
作为一个天真的例子,请考虑下面的 class 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()
输出
!!python/object:__main__.A
a: 0.14285714285714285
b: some text
c: [0.09090909090909091, 0.07692307692307693, 0.058823529411764705, some more text]
和所需的输出:
!!python/object:__main__.A
a: 0.1429
b: some text
c: [0.0909, 0.0769, 0.0588, some more text]
我想这可以用 yaml.representative
以某种干净的方式完成。
我想避免使用字符串 output 的舍入,因为实际的 class 结构可能更复杂(递归等)
为浮点数创建您自己的 repesenter,根据需要格式化浮点数,并用 yaml.add_representer(float, my_custom_repesenter)
替换现有的表示器。
Here 你可以找到浮点数的默认代表。您可以将该代码作为起点,仅更改值不是 [+-].inf
或 .nan
的路径,然后将 value
调整为您想要的精度。
您可以手动四舍五入:
#!/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']))
输出
[0.09090909090909091, 0.07692307692307693, 0.058823529411764705, some more text]
[0.0909, 0.0769, 0.0588, some more text]
您可能需要为极端情况添加更多代码,请参阅 represent_float()
as