如何使用 UliEngineering 在 Python 中转换摄氏/华氏/开尔文温度
在此示例中,我们将使用 UliEngineering 库在三个最常用的温度单位之间转换:摄氏度(°C)、华氏度(°F)和开尔文(K)
我们现在可以使用 UliEngineering.Physics.Temperature 包中的以下函数在温度单位之间转换:
celsius_to_kelvin(temperature)kelvin_to_celsius(temperature)fahrenheit_to_kelvin(temperature)fahrenheit_to_celsius(temperature)
提示: 你可以向大多数 UliEngineering 函数传递数字(如 120)或字符串(如 120 °C 或 0.01 °F)。SI 前缀如 k 和 m 会自动解码。
示例:
convert_temperature.py
from UliEngineering.EngineerIO import auto_print
from UliEngineering.Physics.Temperature import *
# 转换为摄氏度并存储在变量中
temp = fahrenheit_to_celsius("120 °F") # temp = 48.88888888888897
# 自动格式化值并打印。打印 "48.9 °C"
auto_print(fahrenheit_to_celsius, "120 °F")此外,UliEngineering 提供 normalize_temperature_celsius(temp, default_unit="°C"),它接受字符串并自动识别单位(如果没有给出单位,则假设为 default_unit)。
示例:
normalize_temperature_celsius("120 °C") == 120.0normalize_temperature_celsius("120") == 120.0normalize_temperature_celsius(120) == 120.0normalize_temperature_celsius("120 °F") == 48.88888888888897normalize_temperature_celsius("120 K") == -153.14999999999998auto_print(normalize_temperature_celsius, "120 K")打印-153.15 °C
注意虽然 °K 被 UliEngineering 的函数识别,但 K 正确使用时不带度数符号。
还有 normalize_temperature(temp, default_unit="°C"),它等效于 normalize_temperature_celsius(),但它返回以开尔文而不是摄氏度为单位的温度。
Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow