【问题标题】:Simple unit converter in PythonPython中的简单单位转换器
【发布时间】:2015-11-12 11:51:45
【问题描述】:

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

import math
import time
"""Unit Converter"""
#Welcome and variable setting
print ("Welcome to Sam's Unit Converter")
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

感谢您的帮助。

【问题讨论】:

  • 这个问题是关于改进工作代码的。更适合Code Review
  • @FrédéricHamidi 谢谢,我会在那里发帖,我什至不知道它存在。
  • 你的意思是写的很慢?
  • @PeterWood 是的,一旦我完成了所有组合,这将需要很长时间。我还希望增加重量、速度、能量和数据存储。
  • 为了将来的通知,如果您想将您的问题转移到另一个 SE 站点,您可以将其标记为审核并请求将其移动到所需的新站点。

标签: python converter units-of-measurement


【解决方案1】:

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

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]

示例:

In [18]: convert_SI(1, 'm', 'km')
Out[18]: 0.001

In [19]: convert_SI(1, 'km', 'm')
Out[19]: 1000.0

In [20]: convert_SI(1, 'cm', 'm')
Out[20]: 0.01

【讨论】:

  • 谢谢,这就是我的想法,但我不太确定如何。
  • Himanshu 的建议可能对更复杂的问题有好处;不过,我认为您也可以使用另一个转换因子字典将其进一步推广到美国习惯单位。
【解决方案2】:

你可以在这个例子中使用字典。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-04
    相关资源
    最近更新 更多