Enumerate question: Inner looping like in Perl
Bengt Richter
bokr at oz.net
Sun Oct 31 05:11:11 EST 2004
On Sun, 31 Oct 2004 12:28:47 +0200, Pekka Niiranen <pekka.niiranen at wlanmail.com> wrote:
>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':
#XXX# >... #try:
>... for i, char in itr:
>... print 'inner', i, char
>... if char == 'f':
>... break
else:
print "f not found"
#XXX >... #except StopIteration:
#XXX >... # 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
>>
Try above (untested), noting:
>>> itr = enumerate('abcdef')
>>> for i,c in itr:
... print i,c
... if c=='d': break
... else:
... print 'first else'
...
0 a
1 b
2 c
3 d
>>> for i,c in itr:
... print i,c
... if c=='z': break
... else:
... print '2nd else'
...
4 e
5 f
2nd else
Regards,
Bengt Richter
More information about the Python-list
mailing list