8

I'm trying to learn more about list replacement without using Table. I have a list like this:

list = {{{"a", "b", "c"}, {"d", "e", "f"}, {"g", "h", "i"}}}

Now, I want to modify the list elements, i.e. add the position of the respective elements in front of it and replace every element in the list with that:

listMod = {{{1->"a", 2->"b",3->"c"}, {1->"d", 2->"e", 3->"f"}, {1->"g", 2->"h", 3->"i"}}}
MarcoB
  • 67,153
  • 18
  • 91
  • 189
holistic
  • 2,975
  • 15
  • 37

7 Answers7

10
list = {{{"a", "b", "c"}, {"d", "e", "f"}, {"g", "h", "i"}}};
Map[MapIndexed[First@#2 -> #1 &], #, {2}] &@list

(* Out: {{{1 -> "a", 2 -> "b", 3 -> "c"}, {1 -> "d", 2 -> "e", 3 -> "f"},
        {1 -> "g", 2 -> "h", 3 -> "i"}}} *)
MarcoB
  • 67,153
  • 18
  • 91
  • 189
6
list = {{{"a", "b", "c"}, {"d", "e", "f"}, {"g", "h", "i"}}};


Apply[Rule, Map[Transpose[{Range@3, #}] &, list, {2}], {3}]

enter image description here

Or, more generally

num[v_] := Thread[Range@Length@v -> v]

num /@ Catenate@list

Or

Normal @ Map[PositionIndex, list, {2}] /. (a_ -> {b_}) :> b -> a
eldo
  • 67,911
  • 5
  • 60
  • 168
5
MapIndexed[#2[[3]] -> #1 &, list, {3}]

{{{1 -> "a", 2 -> "b", 3 -> "c"}, {1 -> "d", 2 -> "e", 3 -> "f"}, {1 -> "g", 2 -> "h", 3 -> "i"}}}

Original answer

Map[Thread[Range@Length@# -> #] &, list, {2}]

 

MapIndexed[#2[[3]] -> #1 &, list, {3}] == 
Map[Thread[Range@Length@# -> #] &, list, {2}] == listMod

True

user1066
  • 17,923
  • 3
  • 31
  • 49
4

You can use ReplacePart :

list = {{{"a", "b", "c"}, {"d", "e", "f"}, {"g", "h", "i"}}}
ReplacePart[list,x:{i_,j_,k_}:> (k-> Extract[list,x])]  

{{{1 -> "a", 2 -> "b", 3 -> "c"}, {1 -> "d", 2 -> "e", 3 -> "f"}, {1 -> "g", 2 -> "h", 3 -> "i"}}}

ReplacePart[] is known to be not efficient in terms of memory consumption and speed.

The advantage here is that you have a great flexiblity to do more complicated remplacements. For example you can put constraints on the patterns i_,j_,k_,x

andre314
  • 18,474
  • 1
  • 36
  • 69
3
Module[{i = 1}, i++ -> # & /@ #] & /@ # & /@ list

{{{1 -> "a", 2 -> "b", 3 -> "c"}, {1 -> "d", 2 -> "e", 3 -> "f"}, {1 -> "g", 2 -> "h", 3 -> "i"}}}

kglr
  • 394,356
  • 18
  • 477
  • 896
3
MapThread[Rule, {ConstantArray[Range[#3],
     {#, #2}] & @@ Dimensions[list], list}, 3]

{{{1 -> "a", 2 -> "b", 3 -> "c"}, {1 -> "d", 2 -> "e", 3 -> "f"}, {1 -> "g", 2 -> "h", 3 -> "i"}}}

Coolwater
  • 20,257
  • 3
  • 35
  • 64
2

Missed the boat on this... The only thing I can think of that hasn't already appeared is

List@Transpose[With[{i = #}, i -> # & /@ list[[1, ;; , i]]] & /@ {1, 2, 3}]

Although & / @ {1, 2, 3} is basically Table, so I don't know if it counts.

aardvark2012
  • 5,424
  • 1
  • 11
  • 22