37

Starting from these two lists,

var = {a, b, c} 
values = {{1, 2, 3}, {4, 5, 6}, {7, 8 , 9}}

how can I generate a list of rules?

rules = {{a -> 1, b -> 2, c -> 3}, {a -> 4, b -> 5, c -> 6}, {a -> 7, b -> 8, c -> 9}}

This is how far I have got

In: {{a, b, c}, {1, 2, 3}} // Transpose
In: Rule @@@ %
Out: {{a, 1}, {b, 2}, {c, 3}}
Out: {a -> 1, b -> 2, c -> 3}
sjdh
  • 7,757
  • 5
  • 37
  • 47

6 Answers6

34

Another way:

Thread[var -> #] & /@ values
Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263
27

I propose using Inner:

Inner[Rule, var, values\[Transpose], List]

This is faster than other methods presented:

SetAttributes[timeAvg, HoldFirst]

timeAvg[func_] := 
  Do[If[# > 0.3, Return[#/5^i]] & @@ Timing @ Do[func, {5^i}], {i, 0, 15}]

var = Range@70;
values = Array[Times, {500, 70}];

Inner[Rule, var, values\[Transpose], List]; // timeAvg
Map[Rule @@@ Transpose[{var, #}] &, values]; // timeAvg
Thread[var -> #] & /@ values; // timeAvg
MapThread[Rule, {var, #}] & /@ values; // timeAvg
0.009736

0.01248

0.01372

0.01248

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
15

Just do a map on the values, like this:

var = {a, b, c}
values = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
Map[Rule @@@ Transpose[{var, #}] &, values]

This is the output: {{a -> 1, b -> 2, c -> 3}, {a -> 4, b -> 5, c -> 6}, {a -> 7, b -> 8, c -> 9}}

(In your question you have c->5, but I'm assuming this is a mistake:)

Ajasja
  • 13,634
  • 2
  • 46
  • 104
  • 1
    I would use Thread[var -> #]&, or Thread[ Rule[ var, # ]]&, if you prefer, as the function being mapped. It accomplishes the same thing with less code. I'd even be tempted to rewrite it as Thread[var -> #]& /@ values to take advantage of the shorthand notation. – rcollyer Mar 16 '12 at 19:19
14

Another alternative:

MapThread[#1 -> #2 &, {var, #}] & /@ values

or, equivalently

MapThread[Rule, {var, #}] & /@ values
Niki Estner
  • 36,101
  • 3
  • 92
  • 152
6

Just for fun, another alternative using Outer:

Flatten[Outer[Thread[#1 -> #2] &, {var}, values, 1], 1]
Murta
  • 26,275
  • 6
  • 76
  • 166
3
AssociationThread[var, #] & /@ values // Normal

{{a->1,b->2,c->3},{a->4,b->5,c->6},{a->7,b->8,c->9}}


Just for record

GeneralUtilities`AssociatePairs[Transpose[{var, #}]] & /@ values // Normal

{{a->1,b->2,c->3},{a->4,b->5,c->6},{a->7,b->8,c->9}}

yode
  • 26,686
  • 4
  • 62
  • 167