[Tutor] Iterating over list of functions

Alan Gauld alan.gauld at btinternet.com
Wed May 20 17:07:37 CEST 2009


"Robert Berman" <bermanrl at cfl.rr.com> wrote

> Thank you, Christian. This solution was one I was not expecting and am
> glad to receive it. It is one I will explore in greater detail later.

A dictionary of functions is the most common way to tackle 
this fairly common requirement. It combines readability with 
ease of maintenance, there is no chance of using the wrong 
index.

>> Why not use a dictionary to do the heavy lifting for you
>> 
>>  >>> import string
>>  >>> funcs = {1:string.upper, 2:string.lower}
>>  >>> funcs[1]('this is a simple test')
>> 'THIS IS A SIMPLE TEST'
>>  >>> funcs[2]('THIS IS A SIMPLE TEST')
>> 'this is a simple test'


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list