iterblocks cookbook example
Steve Howell
showell30 at yahoo.com
Sun Jun 3 14:57:38 EDT 2007
--- Raymond Hettinger <python at rcn.com> wrote:
> 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.
>
It comes up in the real world for me once very couple
months or so. It's usually when I need to manipulate
data, but I also use the technique to write quick and
dirty tools to analyze code.
> 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]
>
Neat. I like the way you persist ingroup[0] from call
to call.
> 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.
>
Definitely.
____________________________________________________________________________________
Be a better Heartthrob. Get better relationship answers from someone who knows. Yahoo! Answers - Check it out.
http://answers.yahoo.com/dir/?link=list&sid=396545433
More information about the Python-list
mailing list