本文主要是介绍python单位换算例子,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
之前写的代码就是脑子想到啥就写啥,一堆if--slse 确实增加代码量,还能让领导觉得干得非常卖力。但是都是硬编码,代码简直无法直视,今天学了一个比较简单的方法,还把数据结构进行了简单的理解,照着写了下程序,确实是要比if-slse那种想到啥写啥的要好很多,记录一下
上代码
def converter(value,category='length',from_unit='cm',to_unit='in'):
all_units={
'length':[['m',1],['cm',0.01],['in',0.0254]],
'mass':[['kg',1],['g',0.001],['lb',0.4535924]]
}
convert_value = None
if category in all_units.keys():
untits = all_units[category]
if from_unit != untits[0][0]:#如果不是基准单位
# print("从非基准单位过来的")
for unit in untits[1:]: #把每个数组拿出来
if from_unit == unit[0]:
convert_value = value * unit[1]
print("基准单位是",untits[0][0],"换算后是",convert_value)
else:
convert_value = value #是基准单位
if convert_value:
# print("从基准单位到转换单位")
if to_unit == untits[0][0]:#换算单位也是基准单位,直接返回
return convert_value
for unit in untits[1:]: #把每个数组拿出来
if to_unit == unit[0]:#得到的是单位
# print("转换的单位是",to_unit,unit)
convert_value = convert_value/unit[1]#这里的convert_value已经被换算成基准单位了
return convert_value
print("=========我是有底线的===========")
a=converter(20,category='length',from_unit='cm',to_unit='in')
b=converter(20,category='mass',from_unit='lb',to_unit='g')
print(a,'======',b)
其实这些代码是可以抽出来的,做成数据文件存放在其他地方,是不是有所感觉,那些城市名称也可以使用这样的数据结构来存放呢。
all_units={
'length':[['m',1],['cm',0.01],['in',0.0254]],
'mass':[['kg',1],['g',0.001],['lb',0.4535924]]
}
这篇关于python单位换算例子的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!