Python中优雅的条件列表
为了好玩,我正在为Python制作一个单元转换函数 这是我的代码,到目前为止:Python中优雅的条件列表,python,list,python-2.7,conditional-statements,conditional-operator,Python,List,Python 2.7,Conditional Statements,Conditional Operator,为了好玩,我正在为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","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
,在编码端,我可以有效地包括每个单元的所有交替拼写(foot
,foot
,ft
,等)
我真的很重视每个人的意见
谢谢 使用
中的操作符检查容器,可能类似于以下内容:
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
使用集合
foot_units = {"ft.", "feet", "foot"}
然后可以检查集合中的所有权
if(units[0] in foot_units):
...
除此之外,制作一个转换因子字典,该字典指向一个公共转换元素。然后你就可以强迫自己去做最后的决定了
inches -> feet -> yards
inches -> feet -> feet
RemcoGerlich对于这一步有一个很好的解决方案。我会选择一个标准的长度单位,比如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 = {
'foot': 0.3048, # Google search '1 foot in m'
'feet': 0.3048,
'ft': 0.3048,
'yard': 0.9144,
# etc
}
为什么你要接受*单位
,然后反复隐式地强制它是两个值,而不是仅仅接受,比如说,fromunit,tounit
,作为两个独立的参数?另外,如果N比3好得多,那么试图处理N个单位与N-1个其他单位的笛卡尔积将意味着大量的代码。为什么不分两步进行:从fromunit
转换为某个规范单位,然后从规范单位转换为tounit
。那么你只需要N*2if
条件,而不是N**2.+1到abarnert,除了让它从_unit
和到_unit
@abarnert我使用的是*units,因为我最初计划返回用户想要的任意多的转换,一对多转换。这里还有一个建议(BSD或GNU)该工具几乎完全满足您的需要,并且它附带了一个漂亮、相对容易解析的数据文件units.lib
,可用于构建,例如,RemcoGerlich的答案中使用的字典。如果您想简化此过程,我将使用一个1D表将每个单元转换为单个规范单元,而不是2D表,就像OP的代码一样,它将以组合方式爆炸(我们都知道这会有多混乱)。这正是我编写它的方式…但你应该添加一个例子,说明它如何解决OP在第一个地方遇到的问题:同一个单元的多个名称。只需添加“脚”:0.3048,。