gpt4 book ai didi

python - 如何在 Python 中压缩一堆函数?

转载 作者:太空宇宙 更新时间:2023-11-04 07:18:11 25 4
gpt4 key购买 nike

所以我正在尝试制作一个转换单位的程序,这样我就可以避免在我的物理课上使用因子标签方法。我已经弄清楚了它的通用代码,但到最后我将定义 35 个函数。下面是我到目前为止的代码,我希望能够在每个单元之间进行转换。在它们的正下方是使用这些单位的每种可能的转换。问题是我不想为每个可能的转换创建函数。到目前为止我已经完成的代码只适用于其中的几个单元,但可以在这个链接的小饰品中找到它:

             # km  &  m  &  cm  &  mm  &  M  &  ft  &  In 
#km to m | m to km | cm to km | mm to km | M to km | ft to km | In to km
#km to cm | m to cm | cm to m | mm to m | M to m | ft to m | In to m
#km to mm | m to mm | cm to mm | mm to cm | M to cm | ft to cm | In to cm
#km to M | m to M | cm to M | mm to M | M to mm | ft to mm | In to mm
#km to ft | m to ft | cm to ft | mm to ft | M to ft | ft to M | In to M
#km to In | m to In | cm to In | mm to In | M to In | ft to In | In to ft



def km_to_M_conv():
km=float(input("How many km?"))
result = km * .621371192
sentence = '{} km is equal to {} M.'.format(km, result)
print sentence

def M_to_km_conv():
M=float(input("How many m?"))
result = M * 1.60934
sentence = '{} M is equal to {} km.'.format(M, result)
print sentence

def km_to_m_conv():
km=float(input("How many km?"))
result = km * 1000
sentence = '{} km is equal to {} m.'.format(km, result)
print sentence

def mm_to_cm_conv():
mm=float(input("How many mm?"))
result = mm * .1
sentence = '{} mm is equal to {} cm.'.format(mm, result)
print sentence

def cm_to_mm_conv():
cm=float(input("How many cm?"))
result = cm * 10
sentence = '{} cm is equal to {} mm.'.format(cm, result)
print sentence

welcome=input("What would you like to convert?")
if welcome == ("mm to cm"):
mm_to_cm_conv()
if welcome == ("cm to mm"):
cm_to_mm_conv()
if welcome == ("km to M"):
km_to_M_conv()
if welcome == ("M to km"):
M_to_km_conv()

我对 Python 还是很陌生,所以请多多包涵。谢谢!

最佳答案

提取通用代码:

def converter(source, target, factor):
qty = float(input("How many %s?"))
result = qty * factor
print '{} {} is equal to {} {}.'.format(qty, source, result, target)

def km_to_miles(km):
converter('km', 'miles', 0.621371)

更新:

如果你想变得非常聪明,你可以像这样动态生成函数:

CONVERSIONS = (
('km', 'miles', 0.621371),
('metres', 'feet', 3.28084),
('litres', 'gallons', 0.264172),
)

for from, to, factor in CONVERSIONS:
func_name = '%s_to_%s' % (from, to)
func = lambda x: x * factor
globals()[func_name] = func

reverse_func_name = '%s_to_%s' % (to, from)
reverse_func = lambda x: x * (1 / factor)
globals()[reverse_func_name] = reverse_func

关于python - 如何在 Python 中压缩一堆函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32183928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com