MathGroup Archive 2006

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: List Comparison

  • To: mathgroup at smc.vnet.net
  • Subject: [mg67161] Re: List Comparison
  • From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
  • Date: Sun, 11 Jun 2006 02:17:27 -0400 (EDT)
  • Organization: The Open University, Milton Keynes, UK
  • References: <e6e2b7$1uc$1@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

LectorZ wrote:
> Dear experts,
> 
> I want to compare two lists containing sublists and make out of them 3
> result lists.
> The comparison applies to the first two elements of the sublists.
> 
> list1 = {{1, aa, 565}, {1, bb, 566}, {
>   1, cc, 546}, {2, dd, 56}, {2, ff, 56}, {2, ss, 5}}
> list2 = {{1, aa,
>   34}, {1, bb, 66}, {1, cc, 5443}, {2, dd, 76}, {2, ff, 87}, {2, mm,
> 87}}

Hi Lector,

Among many other possibilities, I have chosen a rule-based approach.

In[1]:=
list1 = {{1, aa, 565}, {1, bb, 566}, {1, cc, 546},
     {2, dd, 56}, {2, ff, 56}, {2, ss, 5}};
list2 = {{1, aa, 34}, {1, bb, 66}, {1, cc, 5443},
     {2, dd, 76}, {2, ff, 87}, {2, mm, 87}};

> Result ONE should be:
> 
> If the FIRST element AND the SECOND elements of the sublists are equal,
> then prepend the THIRD elements from list2.
> 
> result1={{1, aa, 565, 34}, {1, bb, 566, 66}, {
>   1, cc, 546, 5443}, {2, dd, 56, 76}, {2, ff, 56, 87}}

In[3]:=
Transpose[{list1, list2}] /.
   {{{x_, y_, z_}, {u_, v_, w_}} /;
      x === u && y === v -> {x, y, z, w},
    {{x_, y_, z_}, {u_, v_, w_}} /;
      x =!= u || y =!= v -> Sequence[]}

Out[3]=
{{1, aa, 565, 34}, {1, bb, 566, 66},

   {1, cc, 546, 5443}, {2, dd, 56, 76},

   {2, ff, 56, 87}}

> Result TWO should be:
> the FIRST element OR the SECOND elements of the sublists are NOT equal,
> then display the difference from the list1 perspective
> 
> result2={{2, ss, 5}}

In[4]:=
Transpose[{list1, list2}] /.
   {{{x_, y_, z_}, {u_, v_, w_}} /;
      x === u && y === v -> Sequence[],
    {{x_, y_, z_}, {u_, v_, w_}} /;
      x =!= u || y =!= v -> {x, y, z}}

Out[4]=
{{2, ss, 5}}

> Result THREE should be:
> the FIRST element OR the SECOND elements of the sublists are NOT equal,
> then display the difference from the list2 perspective
> result3={{2, mm, 87}}

In[5]:=
Transpose[{list1, list2}] /.
   {{{x_, y_, z_}, {u_, v_, w_}} /;
      x === u && y === v -> Sequence[],
    {{x_, y_, z_}, {u_, v_, w_}} /;
      x =!= u || y =!= v -> {u, v, w}}

Out[5]=
{{2, mm, 87}}

> Thanks for your help
> 
> LZ
> 

HTH,
Jean-Marc


  • Prev by Date: Re: Mathematica doesn't know what it's doing.
  • Next by Date: Re: Mathematica doesn't know what it's doing.
  • Previous by thread: RE: List Comparison
  • Next by thread: ? about Rule