Enumerate question: Inner looping like in Perl

Pekka Niiranen pekka.niiranen at wlanmail.com
Sun Oct 31 11:28:47 CET 2004


Steven Bethard wrote:
> 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
> ... 			
Thanks, I decided to catch logical error of not
finding "f" -letter at all with:

 >>> def myiter(contents):
... 	itr = enumerate(contents)
... 	for i, char in itr:
... 		print 'outer', i, char
... 		if char == 'd':
... 			try:
... 				for i, char in itr:
... 					print 'inner', i, char
... 					if char == 'f':
... 						break
... 			except StopIteration:
... 				print "f not found"
...
 >>> contents = list('abcdeg') 				
 >>> myiter(contents)
outer 0 a
outer 1 b
outer 2 c
outer 3 d
inner 4 e
inner 5 g

Not working: Iter() takes care of its own exceptions?
This recurring feeling that writing REALLY correct programs in Python
is not easier than in lower level languages... :(

-pekka-





> 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