12

I have two lists:

list={{1,2,3,5},{5,3,9,11,12},{5,9,10,16}};
list2={{7,89},{96,5},{-6,-98}};

This is the expected result.

{{1->{7,89},2->{7,89},3->{7,89},5->{7,89}},
 {5->{96,5},3->{96,5},9->{96,5},11->{96,5},12->{96,5}},
 {5->{-6,-98},9->{-6,-98},10->{-6,-98},16->{-6,-98}}}

This is my current try.

Thread /@ 
 Thread[Rule[list, 
   MapIndexed[ConstantArray[list2[[First[#2]]], Length[#1]] &, list]]]
m_goldberg
  • 107,779
  • 16
  • 103
  • 257
yode
  • 26,686
  • 4
  • 62
  • 167

8 Answers8

14
Tuples /@ Thread[list -> List /@ list2]
{
 {1 -> {7, 89}, 2 -> {7, 89}, 3 -> {7, 89}, 5 -> {7, 89}},
 {5 -> {96, 5}, 3 -> {96, 5}, 9 -> {96, 5}, 11 -> {96, 5}, 12 -> {96, 5}},
 {5 -> {-6, -98}, 9 -> {-6, -98}, 10 -> {-6, -98}, 16 -> {-6, -98}}
}
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
10
MapIndexed[# -> list2[[#2[[1]]]] &, list, {2}]

or

ReplacePart[list, {i_, j_} :> list[[i, j]] -> list2[[i]]]
WReach
  • 68,832
  • 4
  • 164
  • 269
9
Thread /@ Thread[list -> Hold /@ list2] // ReleaseHold
Thread /@ Thread[list → Unevaluated /@ list2] /. a_ → b_ -> a -> b
Thread /@ Thread[list -> $ /@ list2] /. $ -> (# &)

As to the reason why I used RightArrow as a medium in the second solution, you may want to read this post.

xzczd
  • 65,995
  • 9
  • 163
  • 468
9

Another way to use Thread:

Thread[#, List, 1] & /@ Thread[list -> list2]
{{1 -> {7, 89}, 2 -> {7, 89}, 3 -> {7, 89}, 5 -> {7, 89}}, 
 {5 -> {96, 5}, 3 -> {96, 5}, 9 -> {96, 5}, 11 -> {96, 5}, 12 -> {96, 5}}, 
 {5 -> {-6, -98}, 9 -> {-6, -98}, 10 -> {-6, -98}, 16 -> {-6, -98}}}
m_goldberg
  • 107,779
  • 16
  • 103
  • 257
kglr
  • 394,356
  • 18
  • 477
  • 896
9

MapThread + Outer:

MapThread[Outer[Rule, ##, 1] &, {list, List /@ list2}]

Obfuscatory:

or

o = (\[FivePointedStar] \[Function] \[FivePointedStar] -> #2) /@ # & @@@ ({##}\[Transpose]) &;
o[list, list2]
Michael E2
  • 235,386
  • 17
  • 334
  • 747
7
MapThread[Map[Function[x, Rule[x, #2]], #1] &, {list, list2}]
ubpdqn
  • 60,617
  • 3
  • 59
  • 148
6

I'm late to this party, but I don't see any other answer like this:

 helper[{u_, v_}] := Rule[#, v] & /@ u
 helper /@ Transpose[{list, list2}]
{{1 -> {7, 89}, 2 -> {7, 89}, 3 -> {7, 89}, 5 -> {7, 89}}, 
 {5 -> {96, 5}, 3 -> {96, 5}, 9 -> {96, 5}, 11 -> {96, 5}, 12 -> {96, 5}}, 
 {5 -> {-6, -98}, 9 -> {-6, -98}, 10 -> {-6, -98}, 16 -> {-6, -98}}}

This seems to me to be a nice, simple way of solving the problem.

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
1

This works, and it is easy to understand:

Flatten[MapThread[ Function[{l1, l2}, Map[{# -> l2} &, l1]], {list, list2}], 1]

CElliott
  • 560
  • 2
  • 7