[Tutor] Function in a data structure
Scott Widney
SWidney@ci.las-vegas.nv.us
Tue Jun 24 20:03:01 2003
> Hello All:
> I'd like to put a function in data structure
> and execute it as part of processing the
> structure.
> I have
> >>fd = {'func':[lambda x: x**2]}
>
> How may I execute the lambda statement which
> is the value for fd['func']?
> I've tried:
> apply(fd['func'],(2))
> and apply(fd['func'],2)
> with no luck
>
> Any ideas? Pointers to docs will
> be most welcome also.
>
> using Python 2.2.2
> TIA
> --
"Rodrigues" already gave you your answer, but there is one thing I wanted to
point out:
Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> fd = {'func1':lambda x: x**2, 'func2':lambda x: x**3}
>>> fd['func1'](2)
4
>>> fd['func2'](2)
8
>>> apply(fd['func1'], (2,))
4
>>> apply(fd['func2'], (2,))
8
>>>
You didn't HAVE to put your lambdas in a one item list, though I realize you
may have wanted to....