4
$\begingroup$

I have two lists of string elements:

  lis = {{"Abc","Def"},{"Ghi","Abc"},{"Mno","Pqrs"}};

  abbrPool = {{"Abc","A"},{"Mno","M"}};

I would like to replace certain elements in the first list with the matching second elements from the second list, to give:

  res = {{"A","Def"},{"Ghi","A"},{"M","Pqrs"}}

I can do this by brute force using Cases/DeleteCases, but wonder if there is a more elegant solution.

$\endgroup$

4 Answers 4

4
$\begingroup$

Use ReplaceAll.

lis /. Rule @@@ abbrPool
$\endgroup$
3
$\begingroup$
ReplaceAt[MapApply[Rule] @ abbrPool, {All, 1}] @ lis

{{"A", "Def"}, {"Ghi", "Abc"}, {"M", "Pqrs"}}

$\endgroup$
2
$\begingroup$

Another way using AssociationThread and Lookup:

Map[Lookup[AssociationThread @@ Transpose[abbrPool], #, #] &, lis, {2}] === res

(*True*)

Or using Replace:

Replace[lis, Rule @@@ abbrPool, {2}] === res

(*True*)
$\endgroup$
2
$\begingroup$

Using Lookup:

lis = {{"Abc", "Def"}, {"Ghi", "Abc"}, {"Mno", "Pqrs"}};
abbrPool = {{"Abc", "A"}, {"Mno", "M"}};

lut = Rule @@@ abbrPool
Map[Lookup[lut, #, #] &, lis, {2}]

{{"A", "Def"}, {"Ghi", "A"}, {"M", "Pqrs"}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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