7
$\begingroup$

I have lists

A = {{0,0.1,50,"A"},{200,0.2,120,"E"},{300,0.32,500,"G"},{400,0.33,800,"GO"}}

B={{0,0.1,821,"new1"},{310,0.32,911,"new"}}

I need to modify A with B to get

C = {{{0,0.1,821,"new"},{200,0.2,120,"E"},{310,0.32,911,"new"},{400,0.33,800,"GO"}}

my rule is whenever A[[All,2]] sees the new B[[All,2]] it replaces with that particular vector from B.

I can, of course, use loop and find and replace, is there any simple way to do this job?

$\endgroup$
5
$\begingroup$
A/.Rule@@@Select[Tuples[{A,B}],#[[1,2]]===#[[2,2]]&]

{{0,0.1,821,"new1"},{200,0.2,120,"E"},{310,0.32,911,"new"},{400,0.33,800,"GO"}}

$\endgroup$
4
  • $\begingroup$ @ yode, I appreciate your answer. I am sorry about my ignorance, Could you just give an idea of the use of "@@@" please? I know that @ represents mapping. Is there any difference between == and === ? $\endgroup$ – TM90 Apr 20 '17 at 1:28
  • 1
    $\begingroup$ You can check here and here $\endgroup$ – yode Apr 20 '17 at 1:31
  • $\begingroup$ But work for me. $\endgroup$ – yode Apr 21 '17 at 8:21
  • $\begingroup$ I am sorry, I had made a mistake in the program,Please accept my apology. $\endgroup$ – TM90 Apr 21 '17 at 8:25
4
$\begingroup$

Perhaps (apologies if I have misinterpreted):

A /. ({_, #[[2]], __} -> # & /@ B)
$\endgroup$
3
$\begingroup$

What about:

GatherBy[ Join[A, B], #[[2]] & ][[ All , -1]]

{{0, 0.1, 821, "new1"}, {200, 0.2, 120, "E"}, {310, 0.32, 911, "new"}, {400, 0.33, 800, "GO"}}

If order does not matter:

DeleteDuplicatesBy[Join[B, A], #[[2]] &]
$\endgroup$
2
  • $\begingroup$ Little shorter Last /@ GatherBy[Join[A, B], #[[2]] &] $\endgroup$ – yode Apr 21 '17 at 8:56
  • $\begingroup$ @yode yep, though I decided to use this as it should be faster for bigger lists. $\endgroup$ – Kuba Apr 21 '17 at 9:02
1
$\begingroup$
ClearAll[f]
f[{x__}] := {x};
(f[{_, #[[2]], __}] = #) & /@ B;

f /@ A
{{0, 0.1`, 821, "new1"}, {200, 0.2`, 120, "E"}, {310, 0.32`, 911, "new"},
 {400, 0.33`, 800, "GO"}}
$\endgroup$
1
$\begingroup$

A[[All, 2]] /. Thread[#[[All, 2]] -> #]& @ Join[B, A]

{{0, 0.1, 821, "new1"}, {200, 0.2, 120, "E"}, {310, 0.32, 911, "new"}, {400, 0.33, 800, "GO"}}

$\endgroup$
1
$\begingroup$
Module[{alternatives = Alternatives @@ B[[All, 2]]},
Map[If[MatchQ[#[[2]], alternatives], 
First@Cases[B, {_, #[[2]], ___}], #] &, A]]

(* {{0, 0.1, 821, "new1"}, {200, 0.2, 120, "E"}, {310, 0.32, 911,"new"},
{400, 0.33, 800, "GO"}} *)


A /. {_, x_Real, __} /; MatchQ[x, Alternatives @@ B[[All, 2]]] :> 
First@Cases[B, {_, x, __}]

(* {{0, 0.1, 821, "new1"}, {200, 0.2, 120, "E"}, {310, 0.32, 911,"new"}, 
{400, 0.33, 800, "GO"}} *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.