how to make a generator use the last yielded value when it regains control
John Salerno
johnjsal at NOSPAMgmail.com
Sun Apr 9 01:24:57 EDT 2006
Gerard Flanagan wrote:
> 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?
>
>
> data = [1, 1, 1, 2, 2, 3, 4, 4, 3, 2, 2, 1, 1, 2, 2,4, 2, 2]
>
> from itertools import groupby
>
>
> for k, g in groupby( data ):
> print k, list(g)
>
> 1 [1, 1, 1]
> 2 [2, 2]
> 3 [3]
> 4 [4, 4]
> 3 [3]
> 2 [2, 2]
> 1 [1, 1]
> 2 [2, 2]
> 4 [4]
> 2 [2, 2]
>
> for k, g in groupby( data, lambda x: x<2 ):
> print k, list(g)
>
> True [1, 1, 1]
> False [2, 2, 3, 4, 4, 3, 2, 2]
> True [1, 1]
> False [2, 2, 4, 2, 2]
>
> Gerard
>
Interesting. After following along with the doc example, it seemed like
I had to do complicated stuff with the keys parameter, and I kind of
lost track of it all.
More information about the Python-list
mailing list