Re: Efficient way to merge lists--Programming help

*To*: mathgroup at smc.vnet.net*Subject*: [mg12734] Re: [mg12708] Efficient way to merge lists--Programming help*From*: Carl Woll <carlw at fermi.phys.washington.edu>*Date*: Thu, 4 Jun 1998 02:52:18 -0400*Sender*: owner-wri-mathgroup at wolfram.com

Hi again Joel, One way to do what you want is as follows. Use the second list to define a function which changes {x,y,_} to {x,y,newz}, and then apply this function to the first list. Specifically, define f[{a_,b_,c_}] := g[{a,b,_}] = {a,b,c} g[a_] := a Apply the function f to your second list f /@ test2; Now g is defined such that if {a,b,_} is an element of test2, g[{a,b,d}] will return {a,b,c} from test2, otherwise g will return {a,b,d}. This is exactly what you want, so the next step is to apply g to test1 g /@ test1 which returns the desired list of triples. We can combine the above into a single function replace[test1_, test2_] := Module[{f,g}, f[{a_,b_,c_}] := g[{a,b,_}] = {a,b,c}; g[a_] := a; f /@ test2; g /@ test1 ] I don't know if this is a better solution, but at least I think it's easy to understand how it works. If you knew that the triples were ordered, many other solutions would be possible. Cheers, Carl Woll Dept of Physics U of Washington On Wed, 3 Jun 1998, Joel Cannon wrote: > Cam someone suggest better ways to accomplish the following? > > I have two lists containing triplets--test is a rectangular array of > triplets {x,y,z} (e.g. Dimensions {4,40,3}) and test2 is an array of > triplets (e.g. Dimensions {50,3}). test2 is to replace equivalent > elements in test (when the x and y values are equal--the test2 z values > have been calculated more accurately). > > The task can be understood to be: > > 1. Given a triplet {x_i,y_i,z_i} from test2, find the position in test > which has the same {x_i,y_i,_}. > > 2. Replace the element in test by the triplet from test2. > > > I resorted to a loop after I decided that it would take me too much time > to figure out a better, more elegant solution. Here is what I did: > > For[i=1,i<=Length[test2],i++, > test = ReplacePart[test,test2[[i]], > test//Position[#,{test2[[i]][[1]],test2[[i]][[2]],_}]& //Flatten]]; > > Thanks for any help. > > ------------------------------------------------------------------------------ > Joel W. Cannon | (318)869-5160 Dept. of > Physics | (318)869-5026 FAX Centenary College of > Louisiana | P. O. Box 41188 | > Shreveport, LA 71134-1188 | > > > >