Lists and Indices
Jim Meier
jim at dsdd.org
Thu Aug 8 23:39:09 EDT 2002
On Thu, 08 Aug 2002 06:45:39 -0600, Mark McEahern wrote:
>> I currently use
>>
>> index=1
>> for color in colors:
>> print '%d. %s' % (index, color)
>> index += 1
>>
>> but that does not seem pretty to me;
If you feel the need, try something like this:
>>> 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.
-Jim
More information about the Python-list
mailing list