简体   繁体   English

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

[英]How to condense a bunch of functions in Python?

So I am trying to make a program to convert units so that I can avoid using factor label method in my physics class. 因此,我试图编写一个程序来转换单位,以便避免在物理课中使用因子标签方法。 I've figured out the general code for it, but by the end I will have 35 functions to define. 我已经找到了它的通用代码,但是到最后,我将定义35个函数。 Below is the code I have so far, with each unit I would like to be able to convert between on top. 下面是我到目前为止拥有的代码,每个单元我都希望能够在上面进行转换。 Directly below those is each possible conversion using those units. 在这些值的正下方是使用这些单位进行的每种可能的转化。 The trouble is I would love to not make functions for each of those possible conversions. 问题是我不希望为每个可能的转换都创建函数。 The code which I have completed so far is only for a few of those units, but it can be found in a trinket at this link: 到目前为止,我已经完成的代码仅适用于其中一些单元,但是可以在此链接的小饰品中找到它:

             # 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()

I'm still fairly new to Python so bear with me. 我对Python还是很陌生,所以请多多包涵。 Thanks! 谢谢!

factor out common code: 分解出通用代码:

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)

Update: 更新:

if you want to be really smart you can dynamically generate the functions like this: 如果您想变得真正聪明,可以动态生成如下函数:

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

I would pick a standard length (probably metres) and keep a dictionary (if you don't know what a dictionary is then look them up / play with them a bit as they're very useful) stored of how long each unit is in the standard unit. 我会选择一个标准长度(可能是米)并保留一本字典(如果您不知道字典是什么,那么请查一下它们,因为它们非常有用,请稍作练习)存储每个单元的时间标准单位。 For example: 例如:

conversion_factors_dict = {'m': 1,
                           'cm': 0.01,
                           'ft':0.305}

Then your function has to take a number, a "source" unit and a "destination" unit. 然后,您的函数必须采用数字,“来源”单元和“目的地”单元。 You first convert the source unit into your standard (metres) and then convert that into your destination unit. 您首先将源单位转换为标准(米),然后将其转换为目标单位。 For example: 例如:

def convert(number, source, destination, conversion_factors_dict):
    input_in_metres = number * conversion_factors_dict[source]
    input_in_destination_units = input_in_metres / conversion_factors_dict[destination]
    return "{}{} = {}{}".format(number, source, input_in_destination_units, destination)

A better way to approach this problem is probably by creating grouping all your factors against the choices, under a dictionary and then calling the corresponding values of the keys as per the user input. 解决此问题的更好方法可能是通过在字典下创建针对选择的所有因素分组,然后根据用户输入调用键的相应值。 It may be visualised as : 它可以可视化为:

factors = {'mm to cm' : 0.1, 'cm to mm' : 10, 'km to M' : .621371192} # You may like to define more conversion factors here

welcome = input("What would you like to convert?")
frm, _, to = welcome.split()
distance = input("How many "+frm+" ?")

print (str(distance)+frm+' is equal to ' +str(float(distance)*factors[welcome])+ to

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM