Re: Request for help: working with multi-level lists

*To*: mathgroup at smc.vnet.net*Subject*: [mg13695] Re: Request for help: working with multi-level lists*From*: Denis Foo Kune <kune at stsci.edu>*Date*: Sat, 15 Aug 1998 04:39:25 -0400*Organization*: Space Telescope Science Institute*References*: <6qp3mc$al3@smc.vnet.net>*Sender*: owner-wri-mathgroup at wolfram.com

KCConnolly wrote: > I have a list of 10 elements, each of which is a list of three elements > (let's say in each case an integer, a real number, and a string). I am > looking for the most elegant way to select those first-level elements > (i.e., the lists) whose integer element is equal to a particular value > (let's say "1"), and then to obtain the mean of the real number > elements of the lists selected. For a moderately elegant solution, you could use a simple recursive algorithm as the following: Assuming that your inner list has the following structure: {integer, float, string} -Is the list empty? Yes- return Sum/(N of elements) //The base case No- continue -Is integer == key? Yes- sum=sum+float, N=N+1, and recurse with the rest of the list No- Restart with the rest of the list. this algorithm will go through the list only once and return the mean as demanded. Now for a quick Mathematica code: Helper[lst_,key_,s_,n_]:= If[lst=={} ,s/n ,If[First[First[lst]]==key ,Helper[Rest[lst],key,(s+First[Rest[First[lst]]]),(n+1)] ,Helper[Rest[lst],key,s,n] ] ]; keyMean[lst_,key_]:=Helper[lst,key,0,0] The last line is just the frontend of the small engine. You can just call the function as keyMean[ <list>, <key>] e.g.: keyMean[{{1,2.0,"sdafg"},{4,5.3,"sdfg"},{2,34.4,"fdg"},{1,3.8,"dfg"},{7,4.56, "sgh"}},1] Note that you can also use MemberQ instead of the long "First[Rest[.." thing, but if some of your data happen to look like your key, you might run into problems. Hope that helps. :-Denis