7
$\begingroup$

I have some trouble converting an imported list looking like this:

{{a, b}, {c, d}, {e, f}} 

into a list of rules looking like this:

{{a -> b}, {c -> d}, {e -> f}}
$\endgroup$
5
  • 1
    $\begingroup$ It is a list of lists of rules. But anyway: List@*Rule@@@... $\endgroup$
    – Kuba
    Commented Mar 1, 2019 at 19:24
  • $\begingroup$ Thx. So like this? data = {{a,b},{c,d},{e,f}} data@*Rule@@@ ? $\endgroup$ Commented Mar 1, 2019 at 19:35
  • 9
    $\begingroup$ List@*Rule@@@data $\endgroup$
    – Kuba
    Commented Mar 1, 2019 at 19:42
  • $\begingroup$ Thx. It worked too. $\endgroup$ Commented Mar 1, 2019 at 19:44
  • $\begingroup$ mathematica.stackexchange.com/q/88429 is a very similar question $\endgroup$
    – m_goldberg
    Commented Mar 2, 2019 at 1:32

4 Answers 4

10
$\begingroup$

Why not

list = {{a, b}, {c, d}, {e, f}};
Rule @@@ list

{a -> b, c -> d, e -> f}

This will work as well as

{{a -> b}, {c -> d}, {e -> f}}

in just about every situation where you are likely need a list of rules.

Of course, if you must have the particular form that you show, there is

{#1 -> #2} & @@@ list

and

{#[[1]] -> #[[2]]} & /@ list

and

List @* Rule @@@ list

and

List @@@ Rule @@@ list
$\endgroup$
4
$\begingroup$

Why not:

list1 = {{a,b},{c,d},{e,f}};
list2 = Table[{list[[i, 1]] -> list[[i, 2]]}, {i, 1, Length[list]}]

prints out

{{a -> b}, {c -> d}, {e -> f}}
$\endgroup$
1
  • $\begingroup$ Thx. It worked. $\endgroup$ Commented Mar 1, 2019 at 19:43
1
$\begingroup$
list = {{a, b}, {c, d}, {e, f}};

Using MapApply (new in 13.1)

MapApply[List @* Rule] @ list

{{a -> b}, {c -> d}, {e -> f}}

$\endgroup$
1
$\begingroup$
list = {{a, b}, {c, d}, {e, f}};

Using Cases;

Cases[list, v_ :> List@*Rule @@ v]

(*{{a -> b}, {c -> d}, {e -> f}}*)

Or using MapThread:

MapThread[List@Rule[#1, #2] &, Thread@#] &@list

(*{{a -> b}, {c -> d}, {e -> f}}*)
$\endgroup$

Your Answer

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

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