Re: Replacing list elements while retaining structure

*To*: mathgroup at smc.vnet.net*Subject*: [mg73990] Re: [mg73967] Replacing list elements while retaining structure*From*: Andrzej Kozlowski <akoz at mimuw.edu.pl>*Date*: Mon, 5 Mar 2007 04:46:15 -0500 (EST)*References*: <200703040450.XAA25252@smc.vnet.net>

On 4 Mar 2007, at 05:50, D. Grady wrote: > Okay, so I have two lists, X and Y. X has some complex structure > which is important, but the values contained in X are not important. > Y has values that are important, but the structure of Y is not. I was > to sequentially replace all the elements in X with the elements of Y. > > It's assumed that X and Y have the same total number of elements, i.e. > Length[Flatten[X]] == Length[Flatten[Y]] > > Here is an example: > > In[8]:= > structurize[{x,x,{{x},x},x},{1,2,3,4,5}] > > Out[8]= > {1,2,{{3},4},5} > > This is what I have so far: > > structurize[X_List, Y_List] := ReplacePart[X, Flatten[Y], Position[X, > a_ /; \ > (Head[a] =!= List), Heads -> False], > Table[{i}, {i, 1, Length[ > Flatten[Y]]}]] /; Length[Flatten[X]] == Length[Flatten[Y]] > > This works fine so long as the elements of X are atomic expressions; > however, if there is an element of X which is a more complicated > expression, like x^2, then this function does not work as desired > because the pattern in Position[] matches x^2 as well as x and 2. Is > there a way to avoid matching parts of a subexpression? Is there a > better way to approach the problem from the get-go? > > Thanks in advance! > > Since it does not matter what happens to your values in X you can simply replace them first by some atomic expression. A simple way to do that is to multiply X by 0; it will produce a message if X contains any "infinite" symbols like Ininity, ComplexInfinity, but will work anyway. After that you can eiter use your method or something like this: structurize[values_, structure_] := Module[{st = structure*0, i = 0, g}, g[_] := values[[++i]]; Map[g, st, {-1}]] In[2]:= structurize[Range[5],{x,x,{{x^2},x},x}] Out[2]= {1,2,{{3},4},5} Andrzej Kozlowski

**References**:**Replacing list elements while retaining structure***From:*"D. Grady" <D.C.Grady@gmail.com>

**Re: Hilbert Transform problems**

**accessing a kernel on a network**

**Replacing list elements while retaining structure**

**Re: Replacing list elements while retaining structure**