简体   繁体   中英

Pass arbitrary number of a set of variables to Python Function

I am not sure on the precise way to phrase the question as it is easier to just demonstrate with code. I would like to have a function that accepts a variable number of a set of 3 required and 1 optional arguments. As an illustration, matplotlib.pyplot.plot() can accept any number of (x, y, color) set of variables. I would like to copy this behavior, but I am unsure of the proper way to do this using *args or similar. Below I illustrate the behavior I would like.

myFunc(name, lo, hi, step) # Do something
myFunc(name, lo, hi, step, name2, low2, hi2, step2) # Do something for name and name2
myFunc(name, lo, hi, name2, low2, hi2) # Same as above but use default step for both

The only way I can think of is to loop through the arguments and perform a series of checks on make sure it satisfies the type for (name, lo, hi, step) and to check if step is even given, but I would like to know if there is a more efficient way of doing this.

Edit:

I wanted the above behavior since my function uses the first set to identify a parameter and create a while loop. If any more sets of parameters remain it calls itself recursively to construct a nested while loop with the remaining parameters, etc. If no additional sets remain it will perform some data measurement and then return. This way I can loop through an arbitrarily large multi-dimensional space using a single recursive function.

Is something like this what you're looking for?

list_of_things = [('name', 'lo', 'hi', 'step'),
                  ('name2', 'lo2', 'hi2'), 
                  ('name3', 'lo3', 'hi3', 'step3')
]
def myFunc(name, lo, hi, step='default'):
                              # do something
def callMyFunc(x):    
    for i in x:
        myFunc(*i)            # pass the contents of the tuple as arguments

If you don't want the tuple of items ordered, you would have to name each of the arguments and submit them named.

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