indexed looping, functional replacement?

Bengt Richter bokr at oz.net
Sun Nov 10 02:45:36 EST 2002


On Sat, 9 Nov 2002 20:34:58 -0500, "Raymond Hettinger" <python at rcn.com> wrote:

>> > 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.2, you can roll your own enumerate:
>
>>>> from __future__ import generators
>>>> def enumerate(seq):
>    i = 0
>    for elem in seq:
>        yield (i, elem)
>        i += 1
>
>>>> list(enumerate('later dude'))
>[(0, 'l'), (1, 'a'), (2, 't'), (3, 'e'), (4, 'r'), (5, ' '), (6, 'd'), (7,
>'u'), (8, 'd'), (9, 'e')]
>
also a lazy zip, to avoid building lists you don't use (untested beyond what you see ;-)

 >>> from __future__ import generators
 >>> def xzip(*args):
 ...     for i in xrange(min(map(len,args))):
 ...         yield tuple([x[i] for x in args])
 ...
 >>> for f,s in xzip(fl,sl):
 ...     f(s)
 ...
 f1: bbb
 f2: sdf
 f3: sdw

Regards,
Bengt Richter



More information about the Python-list mailing list