iterblocks cookbook example

Raymond Hettinger python at rcn.com
Sat Jun 2 16:47:15 EDT 2007


On Jun 2, 10:19 am, Steve Howell <showel... at yahoo.com> wrote:
> George Sakkis produced the following cookbook recipe,
> which addresses a common problem that comes up on this
> mailing list:

ISTM, this is a common mailing list problem because it is fun
to solve, not because people actually need it on a day-to-day basis.

In that spirit, it would be fun to compare several different
approaches to the same problem using re.finditer, itertools.groupby,
or the tokenize module.  To get the ball rolling, here is one variant:

from itertools import groupby

def blocks(s, start, end):
    def classify(c, ingroup=[0], delim={start:2, end:3}):
        result = delim.get(c, ingroup[0])
        ingroup[0] = result in (1, 2)
        return result
    return [tuple(g) for k, g in groupby(s, classify) if k == 1]

print blocks('the <quick> brown <fox> jumped', start='<', end='>')

One observation is that groupby() is an enormously flexible tool.
Given a well crafted key= function, it makes short work of almost
any data partitioning problem.


Raymond




More information about the Python-list mailing list