Re: Enumerate question: Inner looping like in Perl

From: Steven Bethard (steven.bethard_at_gmail.com)
Date: 10/30/04

  • Next message: Alex Martelli: "Re: New to Python: Features"
    To: python-list@python.org
    Date: Sat, 30 Oct 2004 18:15:45 +0000 (UTC)
    
    

    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


  • Next message: Alex Martelli: "Re: New to Python: Features"

    Relevant Pages