Sequence splitting

Paul Rubin http
Fri Jul 3 04:39:27 EDT 2009


Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> writes:
> groupby() works on lists.

>>> a = [1,3,4,6,7]
>>> from itertools import groupby
>>> b = groupby(a, lambda x: x%2==1)  # split into even and odd
>>> c = list(b)
>>> print len(c)
3
>>> d = list(c[1][1])    # should be [4,6]
>>> print d  # oops.
[]

> The difference between what I'm suggesting and what groupby() does is 
> that my suggestion would collate *all* the elements with the same key, 
> not just runs of them. This (as far as I can tell) requires returning 
> lists rather than iterators.

I guess that is reasonable.

> The most important difference between my suggestion and that of the OP is 
> that he limited the key function to something which returns a truth 
> value, while I'm looking for something more general which can split the 
> input into an arbitrary number of collated sublists.

Also ok.



More information about the Python-list mailing list