Python 中的简单单位转换器

新手上路,请多包涵

我是编程新手,我正在尝试用 python 制作一个简单的单位转换器。我想将公制单位和公制单位转换为英制单位,反之亦然。我已经开始使用这段代码,但发现这种方法速度慢且效率低下,如何才能更有效地编写代码?

 import math
import time
"""Unit Converter"""
#variable setting
cat = raw_input ("Which category would you like to convert? we support length(l) and Weight(w):  ")
if cat == ("l"):
unit1 = raw_input ("Which unit would you like to convert from: ")
unit2 = raw_input ("Which unit would you like to convert to: ")
num1 = raw_input ("Enter your value: " )

    ##Calculations

if unit1 == "cm" and unit2 == "m":
    ans = float(num1)/100
elif unit1 == "mm" and unit2 == "cm":
    ans = float(num1)/10
elif unit1 == "m" and unit2 == "cm":
    ans = float(num1)*100
elif unit1 == "cm" and unit2 == "mm":
    ans = float(num1)*10
elif unit1 == "mm" and unit2 == "m":
    ans = float(num1)/1000
elif unit1 == "m" and unit2 == "mm":
    ans = float(num1)*1000
elif unit1 == "km" and unit2 == "m":
    ans = float(num1)*1000
elif unit1 == "m" and unit2 == "km":
    ans = float(num1)/1000
elif unit1 == "mm" and unit2 == "km":
    ans = float(num1)/1000000

谢谢你的帮助。

原文由 SalamalCamel 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 839
2 个回答

您可以使用带有转换因子的字典和调用它们的函数。

 def convert_SI(val, unit_in, unit_out):
    SI = {'mm':0.001, 'cm':0.01, 'm':1.0, 'km':1000.}
    return val*SI[unit_in]/SI[unit_out]

例子:

 >>> convert_SI(1, 'm', 'km')
0.001
>>> convert_SI(1, 'km', 'm')
1000.0
>>> convert_SI(1, 'cm', 'm')
0.01

原文由 ryanjdillon 发布,翻译遵循 CC BY-SA 4.0 许可协议

对于那些喜欢使用外部包的人来说, Axiompy 是一个选择。

安装: pip install axiompy

 from axiompy import Units
units = Units()
print(units.unit_convert(3 * units.metre, units.foot))
>>> <Value (9.84251968503937 <Unit (foot)>)>

原文由 anonymousse 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏