Enumerate question: Inner looping like in Perl

Steven Bethard steven.bethard at gmail.com
Sat Oct 30 14:15:45 EDT 2004


Pekka Niiranen <pekka.niiranen <at> wlanmail.com> writes:

> for i, row in enumerate(contents):
> 	row[i] = something
> 	if matcherSTART.search(row):
> 		"Oops! how to advance 'i' and 'row' untill:
> 		if matcherEND.search(row):
> 			continue

Usually I would do this kind of thing by just keeping the iterator around.  The
example below has two loops, an outer and an inner, and both iterate over the
same enumeration.  (I've used 'char ==' instead of regular expressions to make
the output a little clearer, but hopefully you can do the translation back to
regexps for your code.)

>>> contents = list('abcdefg')
>>> itr = enumerate(contents)
>>> for i, char in itr:
... 	print 'outer', i, char
... 	contents[i] = char.upper()
... 	if char == 'd':
... 		for i, char in itr:
... 			print 'inner', i, char
... 			if char == 'f':
... 				break
... 			
outer 0 a
outer 1 b
outer 2 c
outer 3 d
inner 4 e
inner 5 f
outer 6 g
>>> contents
['A', 'B', 'C', 'D', 'e', 'f', 'G']

Steve




More information about the Python-list mailing list