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

Gerard Flanagan grflanagan at yahoo.co.uk
Sat Apr 8 19:37:12 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?


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




More information about the Python-list mailing list