简体   繁体   中英

Can I create a function that reports a list of outputs in Python?

I am trying to get a list of outputs from functions. For example, let's say I define a function called 'compute' as below

def compute(a, b):
    add = a + b
    sub = a - b
    return add, sub

What I want to do next is to create a new function that takes this 'compute' function as an argument and returns a list of outputs of the function, add and sub, as strings.

That is, if I name the function "output_list", I want the function output_list(compute) to return ['add', 'sub'] .

It seems it is supposed to be simple, but I have trouble writing it. What should the code look like?

This is not possible. The names of the local variables inside compute are not known outside of compute . In fact, the local variables very likely do not even exist at runtime at all.

Well, it might defeat the purpose but if you are the one who defines compute function, maybe you could do something like this:

from varname import nameof
def compute(a, b):
    add = a + b
    sub = a - b
    compute.output_list = [ nameof(add), nameof(sub) ]
    return add, sub

>>> compute.output_list
['add', 'sub']

Your question is a bit confusing, how do you want to put a called function " CONTAINS PARAMETERS " as a Parameter for a other function without mentioning the Parameters' values?? its a bit confusing... Now, do you want the Output to be a list of the variables as string or you want to list the variables' results in a list???

I will consider the best scenario that you want to list the results of variables as a list of values for another function..

Code Syntax

def compute(a, b):
    add = a + b
    sub = a - b
    return [add, sub]


def another_function(lista= compute(3, 4)):
    return lista

print(another_function())

OUTPUT

[7, -1]

[Program finished]

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