1
$\begingroup$

I have a list {1,2,3,4,5,6} which I would like to associate to another list {a,b,c} by the rule {1->a,2->a,3->b,4->b,5->c,6->c}

What is the best way to do this without explicitly writing out the associations?

 Table[Rule[{1, 2, 3, 4, 5, 6}[[i]], {a, b, c}[[Ceiling[i/2]]]], {i, 1, 6}]

works but is it the most efficient way?

$\endgroup$
3
$\begingroup$
AssociationThread[{1, 2, 3, 4, 5, 6}, Transpose[{{a, b, c}, {a, b, c}}] // Flatten]

(* <|1 -> a, 2 -> a, 3 -> b, 4 -> b, 5 -> c, 6 -> c|> *)
| improve this answer | |
$\endgroup$
  • $\begingroup$ Also, AssociationThread[{1, 2, 3, 4, 5, 6}, Table[#, 2] & /@ {a, b, c} // Flatten] $\endgroup$ – Bob Hanlon Jun 17 at 23:17
2
$\begingroup$
AssociationThread[#, Riffle[#2, #2]] &[Range[6], {a, b, c}]
 <|1 -> a, 2 -> a, 3 -> b, 4 -> b, 5 -> c, 6 -> c|>
| improve this answer | |
$\endgroup$
2
$\begingroup$
listA = {a,b,c}
listB = Riffle[listA,listA]
MapThread[Rule[#1, #2]&, {Range[6], listB}]
| improve this answer | |
$\endgroup$
0
$\begingroup$

Here's an approach:

ClearAll[distributeAssociation];
distributeAssociation[list1_, list2_] :=
 With[{n = Length@list2},
  Join @@ MapThread[AssociationThread, {
      Partition[list1, Ceiling[Length@list1/n]],
      list2}] /; Positive[n]];
distributeAssociation[_, {}] = {};

distributeAssociation[{1, 2, 3, 4, 5, 6}, {a, b, c}]
(* <|1 -> a, 2 -> a, 3 -> b, 4 -> b, 5 -> c, 6 -> c|> *)
| improve this answer | |
$\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.