
Dec. 1, 2003
5:57 p.m.
I think this would be helpful for lazy coders if some function of itertools cover the use case: (`LIMIT' keyword of SQL)
from groupby import groupby alwaystrue = lambda n: True for k, g in groupby(alwaystrue, range(20), 5): ... print list(g) ... [0, 1, 2, 3, 4] [5, 6, 7, 8, 9] [10, 11, 12, 13, 14] [15, 16, 17, 18, 19]
prototype of this case is groupby(keyfunc, iterable, limit=None). Either, groupby(5, range(20)) is okay but 5 is not a sort of `key'. :)
I'd rather not weigh down groupby() with more options. If you really want only the first 5 of each group, you can use itertools.islice(): for k, g in groupby(alwaystrue, range(20)): print list(itertools.islice(g, 0, 5)) --Guido van Rossum (home page: http://www.python.org/~guido/)