简体   繁体   English

在`pint`中,设置每单位`default_format`

[英]In `pint`, set per-unit `default_format`

Basically the title.基本上是标题。 In pint , is there a way to define the default string formatting per dimension or per unit , instead of 'across the board'?pint ,有没有办法定义每个维度每个单位的默认字符串格式,而不是“全面”?

Stated more precisely: I want to format a quantity's numerical value (ie, magnitude), based on its physical unit.更准确地说:我想根据其物理单位格式化一个数量的数值(即大小)。

Here is what I tried, based on the code shown in the docs :这是我尝试过的,基于文档中显示的代码:

from pint import UnitRegistry, Unit
ureg = UnitRegistry()

# Specific format for km won't stick...
ureg.default_format = ".0f~"
ureg.km.default_format = ".2fP"
ureg.km.default_format  # '.0f~'

# ...as also seen here:
dist = 3 * ureg("km")
time = 500 * ureg("s")
print(f"{dist}, {time}")
# wanted: 3.00 kilometer, 500 s
# got:    3 km, 500 s

Especially when dealing with prices, it's practical to be able to set a 2-digit-default, with all other units having different default format.特别是在处理价格时,能够设置 2 位默认值是实用的,所有其他单位具有不同的默认格式。

PS: I know it's possible to set a default formatting on an individual quantity (eg dist.default_format = '.2f~' ), but that's too specific for my use case. PS:我知道可以为单个数量设置默认格式(例如dist.default_format = '.2f~' ),但这对我的用例来说太具体了。 I want all quantities with the unit 'km' to be displayed with 2 decimals.我希望所有以“km”为单位的数量都显示为两位小数。

I have constructed quite the hacky solution:我已经构建了相当hacky的解决方案:

from pint import UnitRegistry, Quantity
ureg = UnitRegistry()

# Setting specific formats:
formatdict = {ureg.km: '.2fP'} # extend as required
Quantity.default_format = property(lambda self: formatdict.get(self.u, ".0f~"))

# Works:
dist = 3 * ureg("km")
time = 500 * ureg("s")
print(f"{dist}, {time}")  # 3.00 kilometer, 500 s

This works, but I'd be surprised if there isn't a better solution.这有效,但如果没有更好的解决方案,我会感到惊讶。


EDIT编辑

It only works in a limited sense.它只在有限的意义上起作用。 ureg.default_format gets changed as well, which prohibits its use in eg a pandas.DataFrame : ureg.default_format发生了变化,这禁止在例如pandas.DataFrame使用它:

ureg.default_format  # <property at 0x21148ed5ae0>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM