Re: req. list sifting
- To: mathgroup at smc.vnet.net
- Subject: [mg4922] Re: req. list sifting
- From: "Brian J. Albright" <albright at physics.ucla.edu>
- Date: Fri, 4 Oct 1996 00:17:53 -0400
- Organization: UCLA Department of Physics and Astronomy
- Sender: owner-wri-mathgroup at wolfram.com
c. osborne wrote: > > i have developed a piece of mathematica code which generates a list of > results in the form : > {{1, 2, {a->4, b->5, c->6}, 7} , {8 ,9 , {a->10, b->11 ... etc}}. > what i need to to is to sort these results into a new table which > contains all the sublists in which a>0 and b>3 or whatever. > I have not been able to deduce a way of doing this from the > mathematica manual. Can anyone help ?. > thanks. > > C.Osborne > UWCC Earth Sciences > Osbornece at cf.ac.uk Hi. One quick and dirty(tm) way to do this would be as follows: Suppose that you have a list of the form: list = { {1, {a->1, b->3}}, {2, {a->5, b->19}}, {3, {a->12, b->3}} }; and you want, say, to eliminate all the entries for which the second rule evaluates to a "b" that is less than 5. You can define a function that substitutes a null list {} for entries that match b < 5 and then apply the funtion to "list" at level 1. Then flatten the Array to eliminate the "{}" entries, and finally, substitute "List" for the head "func": func[ n_, {a->A_, b->B_} ] /; B < 5 := {}; newlist = Flatten[ Apply[ func, list, 1 ] ] /. func -> List [Output:] {{1, {a -> 1, b -> 3}}, {3, {a -> 12, b -> 3}}} Of course this approach assumes that the order and placement of the rules in the list are always the same, so it's not the most general possible solution. However, this technique can easily be extended to handle more general lists by modifying func in an appropriate fashion. If you do a lot of work with manipulating lists and patterns and you would like to supplement the discussion in the Mathematica book, then I would recommend David Wagner's book "Power Progrmaming with Mathematica," esp. chapters 5 and 6 which deal with functional and rule-based programming. I found the discussion there to be quite lucid and informative. (Much in line with the rest of the book. Though the cover design is pretty lame....) Regards, -Brian -------------------------------------------|---------------------------- Brian J. Albright | Department of Physics and Astronomy, UCLA | Um, yeah. Uh.... Oh gee. albright at physics.ucla.edu | http://bohm.physics.ucla.edu/~albright | [.signature stage fright] -------------------------------------------|---------------------------- ==== [MESSAGE SEPARATOR] ====