# Replace a set of vectors in a list from another set of vectors

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?

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"}}

• @ 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 === ? – TM90 Apr 20 '17 at 1:28
• You can check here and here – yode Apr 20 '17 at 1:31
• But work for me. – yode Apr 21 '17 at 8:21
• I am sorry, I had made a mistake in the program,Please accept my apology. – TM90 Apr 21 '17 at 8:25

Perhaps (apologies if I have misinterpreted):

A /. ({_, #[[2]], __} -> # & /@ B)


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]] &]

• Little shorter Last /@ GatherBy[Join[A, B], #[[2]] &] – yode Apr 21 '17 at 8:56
• @yode yep, though I decided to use this as it should be faster for bigger lists. – Kuba Apr 21 '17 at 9:02
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"}}


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"}}

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"}} *)