Matlab-style mask in Python??
Fredrik Stenberg
mail at fredriks.org
Tue Oct 30 07:21:18 EST 2001
> Hi,
>
> I am a long time Matlab user. I just picked up Python for a short
> while.
> I wonder what should be the best way to do sth like:
>
> Matlab:
> a=[3,4,6,7,2,54,2,1,2]
> idx=a>4 ans: [0,0,1,1,0,1,0,0,0]
> a(idx) ans: [6,7,54]
>
> Python:
> a=[3,4,6,7,2,54,2,1,2]
> idx=map(lambda x: x>4,a) #assume this calculation is lengthy
> #and we don't want to repeat
> last cmd???
>
> While we can always put that into a for loop, then append the ans
> element-by-element.... I feel there should be an easier way in
> Python.
> Any suggestions?
>
Hi
Use filter,
>>> filter(lambda x: x > 4, a)
[6, 7, 54]
You might wana look into numpy (http://www.numpy.org) if
you want todo matlab-like stuff in python.
/fredriks
More information about the Python-list
mailing list