Re: How can this MapAt application be done more efficiently
- To: mathgroup at smc.vnet.net
- Subject: [mg4217] Re: How can this MapAt application be done more efficiently
- From: Paul Abbott <paul at earwax.pd.uwa.edu.au>
- Date: Tue, 18 Jun 1996 03:26:09 -0400
- Organization: University of Western Australia
- Sender: owner-wri-mathgroup at wolfram.com
Joel Cannon wrote: > I have written a function to Drop any zero's from a table of numbers. > Here is an example: > > In[161]:= dropzero[ {{5, 0}, {4, 1}, {3, 2, 0}, {3, 1, 1}} ] > > Out[161]= {{5}, {4, 1}, {3, 2}, {3, 1, 1}} > > I would like to learn how to do it more efficiently. In what I am > doing, the 0's will always occur as the last element of the inner > lists (although it would be nice to have it work in general). DeleteCases does what you want: ?DeleteCases DeleteCases[expr, pattern] removes all elements of expr which match pattern. DeleteCases[expr, pattern, levspec] removes all parts of expr on levels specified by levspec which match pattern. For your expression: expr = {{5, 0}, {4, 1}, {3, 2, 0}, {3, 1, 1}}; we use pattern-matching and a conditional test to delete all zeros (at all levels): DeleteCases[expr, x_ /; x == 0, Infinity] {{5}, {4, 1}, {3, 2}, {3, 1, 1}} Here is a pure function alternative: DeleteCases[expr, _?(# == 0&),Infinity] {{5}, {4, 1}, {3, 2}, {3, 1, 1}} Cheers, Paul _________________________________________________________________ Paul Abbott Department of Physics Phone: +61-9-380-2734 The University of Western Australia Fax: +61-9-380-1014 Nedlands WA 6907 paul at physics.uwa.edu.au AUSTRALIA http://www.pd.uwa.edu.au/Paul _________________________________________________________________ ==== [MESSAGE SEPARATOR] ====