Splitting lists

Scott Ransom ransom at physics.mcgill.ca
Thu Feb 27 10:18:03 EST 2003


"Ferenczi Viktor" <cx at cx.hu> wrote in message news:<mailman.1046321293.2733.python-list at python.org>...
> Are there any fast, simple and elegant method to split a list by a filter
> function?

While not precisely what you are asking, if your lists are large 
and consist of numbers, you may want to use Numeric.
 
> # Common definitions:
> lst=range(10)
> def fn(x): return x<5

import Numeric
arr = arange(10)
# or, converting from a list:  arr = Numeric.asarray(lst)
tl = Numeric.compress(fn(x), arr)
# or
tl = Numeric.compress(arr<5, arr)
fl = Numeric.compress(arr>5, arr)

You can convert the resulting arrays back to lists, if required,
by using:

tl = tl.tolist()
fl = fl.tolist()

Scott




More information about the Python-list mailing list