Lists and Indices

Duncan Booth duncan at NOSPAMrcp.co.uk
Fri Aug 9 10:16:20 CEST 2002


Jim Meier <jim at dsdd.org wrote in 
news:xPG49.120038$f05.6430979 at news1.calgary.shaw.ca:

>>>> class IndexingIterator:
> ...      def __init__(self, iterator):
> ...           self.index = 0
> ...           self.iter = iter(iterator)
> ...      def __iter__(self):
> ...           return self
> ...      def next(self):
> ...           self.index += 1
> ...           return (self.index, self.iter.next())
> ... 
>>>> for i,c in IndexingIterator(['a','b','c']):
> ...      print "%d. %s" % (i,c)
> ... 
> 1. a
> 2. b
> 3. c
>>>>^D
> 
> "IndexingIterator" is a mouthful, you'd probably want to choose a better
> name.
> 
Cleaner would just be to use enumerate from the PEP:

    from __future__ import generators
    def enumerate(collection):
        'Generates an indexed series:  (0,coll[0]), (1,coll[1]) ...'     
        i = 0
        it = iter(collection)
        while 1:
            yield (i, it.next())
            i += 1

When Python 2.3 comes along you can just delete all of the above for the 
same effect.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list