Python 中的简单单位转换器

问题描述 投票:0回答:5

我是编程新手,我正在尝试用 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

感谢您的帮助。

python converters units-of-measurement
5个回答
12
投票

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

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

1
投票

所有标准单位转换(千、百、德卡、基数、十、厘、毫)

更新了 @ryanjdillon 的答案以支持以下任何转换:

convert_si(10, 'kilograms', 'grams')
convert_si(5, 'liter', 'kiloliters')
convert_si(6, 'millimeter', 'meter')
convert_si(1, 'kilo', '') # no need to specify type of measurement
convert_si(4, 'hectometer', 'kilometer')
convert_si(7, 'hecto', 'deka') # no need to specify type of measurement
convert_si(3, 'hectogram', 'decigram')
convert_si(2, 'centiliter', 'kiloliter')
convert_si(2, 'centimeter') # without the 3rd argument converts to base unit

这是代码:

def clean_units(unit):
    unit = unit.rstrip('s')  # remove plural
    words_to_remove = ['meter', 'liter', 'gram']  # remove type of unit
    for word in words_to_remove:
        unit = unit.replace(word, '')
    return unit

def convert_si(val, unit_in, unit_out=''):
    SI = {'milli': 0.001, 'centi': 0.01,
          'deci': 0.1, '': 1.0, 'deka': 10,
          'hecto': 100, 'kilo': 1000}

    unit_in = clean_units(unit_in)
    unit_out = clean_units(unit_out)
    return val*SI[unit_in]/SI[unit_out]

0
投票

您可以在此示例中使用字典。

def handle_one():
  print 'one'

def handle_two():
  print 'two'

def handle_three():
  print 'three'

print 'Enter 1 for handle_one'
print 'Enter 2 for handle_two'
print 'Enter 3 for handle_three'
choice=raw_input()
{
'1':  handle_one,
'2':  handle_two,
'3':  handle_three,
}.get(choice)()

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)>)>

0
投票

您还可以使用名为 pint 的 python 包来实现此目的 - 请参阅此处的文章: https://www.blog.pythonlibrary.org/2021/09/01/unit-conversion-pint/

© www.soinside.com 2019 - 2024. All rights reserved.