-1

I am trying to write a python script that runs a bunch a function that are specified as a dictionary in JSON (this is user input). Here is what the JSON file contains:

{
"tests_to_run": {"find_holes": [],
                 "is_greater": [1.2]
                 }
}

find_holes and is_greater are two functions that I have written, the first taking 0, the second 1 parameter. The idea is to specify these parameters in the list associated with the function key in the JSON dictionary.

I am currently using this dictionary as follows:

functions_dict = {"find_holes": val.find_holes,
                 "is_monotonic": val.is_monotonic}

def run_functions(dict_tests_to_run):
    for func, params in dict_tests_to_run.iteritems():
        if params==[]:
            functions_dict[func](time_series)
        if len(params)==1:
            functions_dict[func](time_series, params[0])

It seems a bit awkward to manually check for the length of the parameters, in particular since I am going to have to extend the loop to accomodate functions with up to at least 4 parameters. Is there any better way of doing this?

Thanks, Anne

4

1 回答 1

2

You can use the * operator to expand your list into function parameters. For example,

f(1,2,3)

is equivalent to:

a=[1,2,3]
f(*a)
于 2013-08-02T14:10:36.537 回答