Splitting lists
ATOM
arthur.tomas at web.de
Fri Mar 7 16:06:30 CET 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?
>
> My current solutions with their shortcomings:
>
> # Common definitions:
> lst=range(10)
> def fn(x): return x<5
>
> # Solution 1:
> tl=[e for e in lst if fn(e)]
> fl=[e for e in lst if not fn(e)]
> # fn(e) must be evaluated twice, list must be traversed two times
>
> # Solution 2:
> tl=[]
> fl=[]
> for e in lst:
> if fn(e): tl.append(e)
> else: fl.append(e)
> # Relatively slow
>
> # Solution 3:
> cl=[(e,fn(e)) for e in lst]
> tl=[e[0] for e in cl if e[1]]
> fl=[e[0] for e in cl if not e[1]]
> # Eats up memory, list must be traversed three times
>
> Is there any internal function to do the above?
>
> I need something like: tl,fl=lst.split(fn)
>
> Thanks: Complex
Hi Viktor,
I do not use filter, it is rather a kind of
a ? b : c known from C/C++,
but what about that:
=============================================================
lst = range(10)
tl = []
fl = []
f = lambda e: (e<5 and tl.append(e)) or (e>=5 and fl.append(e))
def mySplit(list):
for item in list:
f(item)
return tl, fl
mySplit(lst)
([0, 1, 2, 3, 4], [5, 6, 7, 8, 9])
=============================================================
Only in haskell-like-language we can write it more elegant, i suppose... :-)
Best greetings!
ATOM
(arthur.tomas at web.de)
More information about the Python-list
mailing list