RE: defining a transform from two lists
- To: mathgroup at smc.vnet.net
- Subject: [mg40877] RE: [mg40837] defining a transform from two lists
- From: "Wolf, Hartmut" <Hartmut.Wolf at t-systems.com>
- Date: Tue, 22 Apr 2003 06:50:37 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
>-----Original Message----- >From: Nathan Moore [mailto:nmoore at physics.umn.edu] To: mathgroup at smc.vnet.net >Sent: Monday, April 21, 2003 12:59 PM >To: mathgroup at smc.vnet.net >Subject: [mg40877] [mg40837] defining a transform from two lists > > >Suppose I have two lists of similar length, > p1={n[i],a[i]} >and > p2 = {n[i],b[i]} >and I'd like to create a new list, > p3 = { n[i], f[ a[i], b[i] ] } >if the new list comes from one parent list then it is >relatively simple to >write and apply a transform w/ map like > h[{x_,y_}]:={x,f[y]} > newlist = h/@list or = Map[h,list] >but two parent lists confuse me > >thanks again! > >Nathan Moore, >University of Minnesota Physics > > Nathan, to me it is not quite clear what constitutes your problem; esp. what disturbs me is your expression "similar length". To make up a simple example first, lets assume p1 and p2 are of the same length, with same keys n[i] and of same order (in the keys). Then Map just extends to MapThread: In[1]:= p1 = {#, #^2} & /@ Range[10] In[2]:= p2 = {#, #^3} & /@ Range[10] In[4]:= MapThread[{#1, f[#2, #4]} &, Join @@ Transpose /@ {p1, p2}] Out[4]= {{1, f[1, 1]}, {2, f[4, 8]}, {3, f[9, 27]}, {4, f[16, 64]}, {5, f[25, 125]}, {6, f[36, 216]}, {7, f[49, 343]}, {8, f[64, 512]}, {9, f[81, 729]}, {10, f[100, 1000]}} Now assuming, there are not all the same keys in both lists (and they may be of different lengths) In[5]:= pp1 = Delete[p1, {{3}, {5}, {9}}] In[6]:= pp2 = Delete[p2, {{1}, {5}, {6}, {8}}] Then just intersect the original lists to common keys: In[7]:= ppp1 = Intersection[pp1, pp2, SameTest -> (First[#1] === First[#2] &)] In[8]:= ppp2 = Intersection[pp2, pp1, SameTest -> (First[#1] === First[#2] &)] In[9]:= MapThread[{#1, f[#2, #4]} &, Join @@ Transpose /@ {ppp1, ppp2}] Out[9]= {{2, f[4, 8]}, {4, f[16, 64]}, {7, f[49, 343]}, {10, f[100, 1000]}} The result is ordered with the keys. If you want to keep the order of the keys of one list (say the first here), then tag that list and re-sort the result: In[10]:= q1 = Last /@ Sort[{Random[], #} & /@ pp1] Out[10]= {{4, 16}, {7, 49}, {6, 36}, {2, 4}, {1, 1}, {8, 64}, {10, 100}} In[12]:= qq1 = Transpose[Join[Transpose[q1], {Range[Length[q1]]}]] In[13]:= qqq1 = Intersection[qq1, pp2, SameTest -> (First[#1] === First[#2] &)] Out[13]= {{2, 4, 4}, {4, 16, 1}, {7, 49, 2}, {10, 100, 7}} In[14]:= Rest /@ Sort[ MapThread[{#3, #1, f[#2, #5]} &, Join @@ Transpose /@ {qqq1, ppp2}]] Out[14]= {{4, f[16, 64]}, {7, f[49, 343]}, {2, f[4, 8]}, {10, f[100, 1000]}} -- Hartmut Wolf