Splitting lists

William Park opengeometry at yahoo.ca
Thu Feb 27 00:44:11 EST 2003


Ferenczi Viktor <cx at cx.hu> wrote:
> 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

Read the documentation, ie. filter().  Also, your 2nd method isn't that
bad.  Try it, you'd be surprised.

-- 
William Park, Open Geometry Consulting, <opengeometry at yahoo.ca>
Linux solution for data management and processing. 




More information about the Python-list mailing list