4
$\begingroup$

Is there a way to create a two-way association or a bijection between two lists of equal length? I know I can use AssociationThread twice, flipping the arguments, but how can I create a bijective function which associates each element in one list with an element of another, and vice-versa?

$\endgroup$
  • $\begingroup$ In what way does the solution you mention fall short of what you want? $\endgroup$ – Alan Sep 13 '16 at 3:21
  • $\begingroup$ @Alan its more clunky: using two variables instead of one. $\endgroup$ – Matt G Sep 13 '16 at 3:24
4
$\begingroup$

A bijective function:

list1 = {1, 2, 3, 4};
list2 = {5, 6, 7, 8};
MapThread[(f[#] = #2; f[#2] = #) &, {list1, list2}]

f[2]
(* Out: 6 *)

And the AssociationThread solution that you mention:

f = <|AssociationThread[list1 -> list2], AssociationThread[list2 -> list1]|>;

f[2]
(* Out: 6 *)
$\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.