how to make a generator use the last yielded value when it regains control

Michael Spencer mahs at telcopartners.com
Sat Apr 8 19:40:50 EDT 2006


John Salerno wrote:
> Michael Spencer wrote:
> 
>> itertools.groupby makes this very straightforward:
> 
> I was considering this function, but then it seemed like it was only 
> used for determing consecutive numbers like 1, 2, 3 -- not consecutive 
> equivalent numbers like 1, 1, 1. But is that not right?


With one argument, groupby assembles groups of equal consecutive elements:
 >>> list((key, list(group)) for key, group in groupby("AAABBCAAA"))
[('A', ['A', 'A', 'A']), ('B', ['B', 'B']), ('C', ['C']), ('A', ['A', 'A', 'A'])]

With a second keyfunc argument, groupby assembles groups where keyfunc(element) 
is equal for consecutive elements
 >>> list((key, list(group)) for key, group in groupby("AAAaaaAAA",str.isupper))
[(True, ['A', 'A', 'A']), (False, ['a', 'a', 'a']), (True, ['A', 'A', 'A'])]
 >>>

HTH
Michael




More information about the Python-list mailing list