我正在为Python创建一个单元转换函数。
这是我的代码,到目前为止:
def UnitConverter(number,*units):
if units == ("feet","inches"):
return number*12
elif units == ("ft","yd"):
return number/3
你可能知道我是如何做这项工作的。
因为我对优雅,良好的代码练习和整体流程非常着迷,除了我的主要问题之外,我想知道你的编码员一般会怎么想:如何有效地检查列表if
陈述中的排列?
示例:是否有一种有效的方法可以使其发挥作用?
def UnitConverter(number,*units):
if units == (("feet" or "foot" or "ft."),("inches" or "in" or "in.")):
return number*12
elif units == ("ft","yd"):
return number/3
如果没有,是否有办法重构我的程序,以便某人可以在编码端以某种方式输入三个参数number
,unit1
,unit2
,我可以有效地包括每个单元的所有替代拼写(feet
,foot
,ft
,etc
)?
我非常重视每个人的意见。
谢谢!
答案 0 :(得分:4)
使用套装。
foot_units = {"ft.", "feet", "foot"}
然后你可以检查集合中的所有权。
if(units[0] in foot_units):
...
除此之外,创建一个转换为公共转换元素的conversion_factor字典。然后你可以强迫你的决赛。
inches -> feet -> yards
inches -> feet -> feet
RemcoGerlich为这一步提供了很好的解决方案。
答案 1 :(得分:4)
我会选择一个标准的长度单位,让我们说m。然后我会有一个字典,为每个其他单位提供一个因子,然后转换:
conversion_factors = {
'foot': 0.3048, # Google search '1 foot in m'
'yard': 0.9144,
# etc
}
def unit_convert(number, from_unit='m', to_unit='m'):
m = number * conversion_factor[from_unit]
return m / conversion_factor[to_unit]
对于同义词(英尺,英尺等),您可以制作第二个字典并在第一个字典中查找规范名称:
conversion_factors = { ... } # as above
synonyms = {
'feet': 'foot',
'ft': 'foot',
...
}
def unit_convert(number, from_unit='m', to_unit='m'):
from_unit = synonyms.get(from_unit, from_unit)
to_unit = synonyms.get(to_unit, to_unit)
# etc
...或者只是多次将它们放在conversion_factors
字典中:
conversion_factors = {
'foot': 0.3048, # Google search '1 foot in m'
'feet': 0.3048,
'ft': 0.3048,
'yard': 0.9144,
# etc
}
答案 2 :(得分:2)
可能类似于以下内容,使用检查包含的in
运算符:
def UnitConverter(number,*units):
feet = {'feet', 'foot', 'ft.'}
inches = {'inches', 'in', 'in.'}
yards = {'yard', 'yd', 'yd.'}
if units[0] in feet and units[1] in inches:
return number*12
elif units[0] in feet and units[1] in yards:
return number/3