Suggesting a new feature - "Inverse Generators"

Michael Spencer mahs at telcopartners.com
Fri Mar 25 17:46:12 CET 2005


Tim Hochberg wrote:
> Jordan Rastrick wrote:
> 

itertools.groupby enables you to do this, you just need to define a suitable 
grouping function, that stores its state:

For example, if short lines should be appended to the previous line:

from itertools import groupby
linesource = """\
Here is a long line, long line, long line
and this is short
and this is short
Here is a long line, long line, long line
and this is short""".splitlines()

def record(item, seq = [0]):
     if len(item) > 20:
         seq[0] +=1
     return seq[0]


  >>> for groupnum, lines in groupby(linesource, record):
  ...     print "".join(lines)
  ...
  Here is a long line, long line, long lineand this is shortand this is short
  Here is a long line, long line, long lineand this is short
  >>>

Michael




More information about the Python-list mailing list