Re: help with lists operations
- To: mathgroup at smc.vnet.net
- Subject: [mg67843] Re: help with lists operations
- From: Bill Rowe <readnewsciv at earthlink.net>
- Date: Mon, 10 Jul 2006 06:37:57 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
On 7/9/06 at 4:50 AM, omk at iname.com (omk) wrote: >Hi ALL, I am a novice in Mathematica, know that there are no easy >ways for learning, so spent 2 weeks trying to solve an easy problem, >but so far have only ugly solutions. Yes, I read and reread the Book >as well as searched for similar problems on the Forum. I have 2 >lists: f1={{2, 1}, {3, 1}, {7, 2}, {9, 1}, {10, 1}, {12, 1}, {14, >3}, {19, 3}, {23, 1}, {24, 1}, {25, 1}} f2={{2, 2}, {5, 1}, { 6, 2}, >{10, 1}, {14, 3}, {16, 1}, {18, 1}, {21, 3}, {22, 1}, {26, 1}} I >need to compare sublists (pairs) from the first list f1 with pairs >from f2. If pairs with 2 first equal numbers exist, I have to >multiply the second, after having products for all such pairs, I >need to receive their sum. Say from f1 and f2 I have {2,1} and >{2,2}, the product is 1 2=2, similar {10,1} and {10,1},{14,3} and >{14,3}, so it should be 2+1+9=12 Any ideas are very welcome TIA, omk First, I can find all common first elements with In[5]:= commonFirstElement=Intersection[First/@f1,First/@f2] Out[5]= {2,10,14} Now I can select pairs with these first elements using pattern matching as follows In[6]:= Cases[f1,{Alternatives@@commonFirstElement,_}] Out[6]= {{2, 1}, {10, 1}, {14, 3}} Similarly, for f2 In[7]:= Cases[f2,{Alternatives@@commonFirstElement,_}] Out[7]= {{2, 2}, {10, 1}, {14, 3}} forming the dot product using the last element of each pair will give you the desired result, i.e., In[8]:= (Last/@Cases[ f1,{Alternatives@@ commonFirstElement,_}]).(Last/@ Cases[f2,{Alternatives@@commonFirstElement,_}]) Out[8]= 12 -- To reply via email subtract one hundred and four