为了好玩,我正在为Python制作一个单元转换函数。
到目前为止,这是我的代码:
def UnitConverter(number,*units):
if units == ("feet","inches"):
return number*12
elif units == ("ft","yd"):
return number/3你可能知道我是怎么做这件事的。
因为我痴迷于优雅、良好的代码实践和总体流程,所以我想知道你们程序员对此的总体看法,以及我的主要问题:如何有效地检查语句中的排列列表
有什么有效的方法让这件事成功吗?
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)?
我真的很重视每个人的意见。
谢谢!
发布于 2013-10-25 20:03:38
我会选择一个标准的长度单位,比如说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]对于同义词(英尺、ft等),您可以制作第二个字典,并在第一个字典中查找规范名称:
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...or只是多次将它们放在conversion_factors字典中:
conversion_factors = {
'foot': 0.3048, # Google search '1 foot in m'
'feet': 0.3048,
'ft': 0.3048,
'yard': 0.9144,
# etc
}发布于 2013-10-25 19:57:15
使用集合。
foot_units = {"ft.", "feet", "foot"}然后你可以在集合中检查所有权。
if(units[0] in foot_units):
...除此之外,还可以创建一个conversion_factor字典,该字典将转到一个常见的转换元素。然后你可以强迫你进入期末考试。
inches -> feet -> yards
inches -> feet -> feet对于这个步骤,RemcoGerlich有一个很好的解决方案。
发布于 2013-10-25 19:56:58
使用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/3https://stackoverflow.com/questions/19598382
复制相似问题