[Tutor] Iterating over list of functions
Lie Ryan
lie.1296 at gmail.com
Wed May 20 16:42:34 CEST 2009
Robert Berman wrote:
> Hi,
>
> Given a list of options: option_1.......option_n. For each option I have
> a corresponding function: func_1..... func_n. I have all function names
> defined in a list similar to flist = [func_1, func_2,.......func_n]
> which I know is a legitimate construct having found a similar construct
> discussed by Kent Johnson in 2005.
>
> What I do not know how to do is to call the selected function. If the
> index of options is 1, then I want to call func_2; do I code
> flist[index]? I do not think Python has a branch indirect construct so I
> cannot use anything similar to that methodology. What is the best
> approach to take to solve this problem?
>
Functions in python is first-class object. It can be passed around like
regular objects, and can be put into lists like regular objects.
opts = [opt1, opt2, opt3]
funcs = [func1, func2, func3]
for f, o in zip(funcs, opts):
f(o)
funcs[1](o[0]) # equivalent to func2(opt1)
More information about the Tutor
mailing list