indexed looping, functional replacement?
Alex Martelli
aleax at aleax.it
Sat Nov 9 14:00:21 EST 2002
Brian O. Bush wrote:
> I currently have a list of functions and a list of arguments to the
> functions (n to n). Is there a way I can get around having to keep an
> index into the arguments as I loop through the functions. Below is my
> imperative approach:
>
> def f1(str):
> print "f1:", str
> def f2(str):
> print "f2:", str
> def f3(str):
> print "f3:", str
>
> str = ["bbb", "sdf", "sdw"]
> fn = [f1, f2, f3]
>
> i = 0
> for f in fn:
> f(str[i])
> i = i + 1
>
> I would like a simpler approach to avoid having to manually maintain
> an index, maybe functional if possible.
In Python 2.3, the enumerate built-in will do just that:
[alex at lancelot alf]$ python2.3
Python 2.3a0 (#4, Nov 6 2002, 09:18:17)
[GCC 2.96 20000731 (Mandrake Linux 8.2 2.96-0.76mdk)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> for x in enumerate('ciao'): print x
...
(0, 'c')
(1, 'i')
(2, 'a')
(3, 'o')
>>>
In Python 2.2, you can try various inferior alternatives, e.g.:
for f, i in zip(fn, range(len(fn))):
f(str(i))
Alex
More information about the Python-list
mailing list