my array subset method could be improved?

Peter peter at commonlawgov.org
Fri Oct 14 09:15:02 EDT 2005


Jim O'D wrote:

>Hi all
>
>I have an array a=array([2,3,1]).
>
>I want to extract an array with all the elements of a that are less than 0.
>
>Method 1.
>new = array([i for i in a if i < 0])
>
>Method 2.
>new = a[nonzero(a<0)]
>
>I'm using Numeric arrays but can't seem to find a function that does this.
>
>Am I missing a more obvious way to do it quickly?
>
>Thanks
>
>Jim
>  
>
You could use filter (which is planned to be removed in Py3000). E.g. 
"array(filter(lambda x: x < 0, (-1, 2, -4, 5, 55, 9, -73, 5)))"

I tend to like "array(i for i in (-1, 2, -4, 5, 55, 9, -73, 5) if i < 
0)" better though. (And its even shorter).

HTH,
Peter




More information about the Python-list mailing list