简体   繁体   中英

Function with varying number of outputs

I am trying to build a python function that loads saved models specified by the user. I would like to design the function so that the user can provide any number of models. As a result, the number of outputs could vary.

A user might use the function in the following way.

model1, model2 = getmodel(model1,model2)

model1, model2, model3 = getmodel(model1,model2,model3)

So far I haven't made it very far.

def getmodel(*models):

    pass

How would I setup my function achieve what I am looking for ? Within the function definition, there is another function "load_function" that I can use to load any individual model.

You could use a tuple or a list containing a varying number of models.

Something like :

model1, model2 = getmodel((model1,model2))

And :

def getmodel(models):
    loaded_models = []
    for model in models:
        loaded_models.append(model_loading_function(model))
    return loaded_models
def getmodel(*models):
    all_models=[]
    for model in models:
            all_models.append(load_function(model))
    return all_models

Using a star on your argument allows it to accept any number of inputs, converting them to a list.

When a list is returned, python will automatically unpack the values into separate variables if you try to set them all equal to one list.

a, b, c = ["apple", "bee", "cat"]

This way, although the getmodel function returns a list, it will be assigned to the individual variables.

只需使用map

model1, model2, model3 = map(your_load_model_function, (model1, model2, model3))
def load_model(model):
  return "loaded : "+model # Replace by actual logic

def load_models(*models):
    result = tuple( load_model(model) for model in models)
    if len(result) == 1:
      return result[0]
    return result

modelA = load_models("modelA") or load_model("modelA")

modelB, modelC = load_models("modelB", "modelC")

print(modelA,modelB,modelC)

With these two functions, you can handle any use cases and it will be convenient for your users. To return multiple values in python you can return a tuple or a list, that the user can unpack.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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