7

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}}
m_goldberg
  • 107,779
  • 16
  • 103
  • 257
user3483676
  • 247
  • 1
  • 5

4 Answers4

10

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
m_goldberg
  • 107,779
  • 16
  • 103
  • 257
4

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}}
Valacar
  • 970
  • 5
  • 14
1
list = {{a, b}, {c, d}, {e, f}};

Using MapApply (new in 13.1)

MapApply[List @* Rule] @ list

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

eldo
  • 67,911
  • 5
  • 60
  • 168
1
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}})

E. Chan-López
  • 23,117
  • 3
  • 21
  • 44