<div dir="ltr">On 21 April 2013 01:13, Steven D'Aprano <span dir="ltr"><<a href="mailto:steve+comp.lang.python@pearwood.info" target="_blank">steve+comp.lang.python@pearwood.info</a>></span> wrote:<br><div class="gmail_extra">
<div class="gmail_quote"><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex"><div class="im"><span style="color:rgb(34,34,34)">I wouldn't use groupby. It's a hammer, not every grouping job is a nail.</span><br>
</div>
<br>
Instead, use a simple accumulator:<br>
<br>
<br>
def group(lines):<br>
accum = []<br>
for line in lines:<br>
line = line.strip()<br>
if line == 'Starting a new group':<br>
if accum: # Don't bother if there are no accumulated lines.<br>
yield accum<br>
accum = []<br>
else:<br>
accum.append(line)<br>
# Don't forget the last group of lines.<br>
if accum: yield accum<br></blockquote><div><br></div><div style>Whilst yours is the simplest bar Dennis Lee Bieber's and nicer in that it yields, neither of yours work for empty groups properly.</div><div style><br>
</div><div style>I recommend the simple change:</div><div style><br></div><div style><div>def group(lines):</div><div> accum = None</div><div> for line in lines:</div><div> line = line.strip()</div><div> if line == 'Starting a new group':</div>
<div> if accum is not None: # Don't bother if there are no accumulated lines.</div><div> yield accum</div><div> accum = []</div><div> else:</div><div> accum.append(line)</div>
<div> # Don't forget the last group of lines.</div><div> yield accum</div><div><br></div><div style>But will recommend my own small twist (because I think it is clever):</div></div><div style><br></div><div style>
<div>def group(lines):</div><div><span class="" style="white-space:pre"> </span>lines = (line.strip() for line in lines)</div><div><br></div><div><span class="" style="white-space:pre"> </span>if next(lines) != "Starting a new group":</div>
<div><span class="" style="white-space:pre"> </span>raise ValueError("First line must be 'Starting a new group'")</div><div><br></div><div><span class="" style="white-space:pre"> </span>while True:</div>
<div><span class="" style="white-space:pre"> </span>acum = []</div><div><br></div><div><span class="" style="white-space:pre"> </span>for line in lines:</div><div><span class="" style="white-space:pre"> </span>if line == "Starting a new group":</div>
<div><span class="" style="white-space:pre"> </span>break</div><div><br></div><div><span class="" style="white-space:pre"> </span>acum.append(line)</div><div><br></div><div><span class="" style="white-space:pre"> </span>else:</div>
<div><span class="" style="white-space:pre"> </span>yield acum</div><div><span class="" style="white-space:pre"> </span>break</div><div><br></div><div><span class="" style="white-space:pre"> </span>yield acum</div></div>
</div></div></div>