2
$\begingroup$

I have two lists:

 lis1= {{8, 11}, {5, 3}, {1, 9}, {7, 2}, {10, 4}, {12, 6}}
 list2= {{1, "1DD"}, {2, "1CD"}, {3, "2DD"}, {4, "2DC"}, {5, "1DD"},{6, 
 "1CD"}, {7, "2DD"}, {8, "2DC"}, {9, "1DD"}, {10, "1CD"}, {11,"2DD"},{12, "2DC"}}

And I need to create a third, replacing elements of list2 in list1 according with the first number, so the out is:

out= {{{8, "2DC"},{11,"2DD"}},{{5, "1DD"},{3, "2DD"}}...}
$\endgroup$
  • 1
    $\begingroup$ Transpose /@ Transpose[{lis1, Replace[lis1, Rule @@@ list2, 2]}]? $\endgroup$ – kglr Apr 8 '18 at 2:19
  • $\begingroup$ if the ordering is irrelevant, you can also use GatherBy[list2, Position[lis1, First[#]][[1, 1]] &] $\endgroup$ – AccidentalFourierTransform Apr 8 '18 at 2:23
3
$\begingroup$

I'd make an Association[]:

assoc = Association[#[[1]] -> # & /@ {{1, "1DD"}, {2, "1CD"}, {3, "2DD"}, {4, "2DC"},
                                      {5, "1DD"}, {6, "1CD"}, {7, "2DD"}, {8, "2DC"},
                                      {9, "1DD"}, {10, "1CD"}, {11, "2DD"}, {12, "2DC"}}]

and then

Map[assoc, {{8, 11}, {5, 3}, {1, 9}, {7, 2}, {10, 4}, {12, 6}}, {2}]
   {{{8, "2DC"}, {11, "2DD"}}, {{5, "1DD"}, {3, "2DD"}}, {{1, "1DD"}, {9, "1DD"}},
    {{7, "2DD"}, {2, "1CD"}}, {{10, "1CD"}, {4, "2DC"}}, {{12, "2DC"}, {6, "1CD"}}}
$\endgroup$
3
$\begingroup$
Replace[lis1, # -> {##} & @@@ list2, 2]

{{{8, "2DC"}, {11, "2DD"}}, {{5, "1DD"}, {3, "2DD"}}, {{1, "1DD"}, {9, "1DD"}},
{{7, "2DD"}, {2, "1CD"}}, {{10, "1CD"}, {4, "2DC"}}, {{12, "2DC"}, {6, "1CD"}}}

$\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.