# Return a string from a vector containing a string and a number

I currently have a List of the form,

{{String_1, 8.}, {String_2, 101.}, {String_3, 37.}, ..., {String_n, 28.}}


Along with another list,

{{8, 37, ... }, ..., {..., 28, 101}}


And I would like to return,

{{String_1, String_3, ...}, ..., {..., String_n, String_2}}


In short, I would like to replace the lists of numbers in the second list with their corresponding strings (given in the first list). I imagine this has quite a simple solution, but searching through Mathematica's documentation hasn't been very fruitful. Any help is appreciated.

• {{8, 37, ... }, ..., {..., 28, 101}} /. (#2 -> #1 & @@@ {{String_1, 8.}, {String_2, 101.}, {String_3, 37.}, ..., {String_n, 28.}}) or {{8, 37, ... }, ..., {..., 28, 101}} /. (Rule @@@ Reverse /@ {{String_1, 8.}, {String_2, 101.}, {String_3, 37.}, ..., {String_n, 28.}})? – J. M. will be back soon Nov 5 '12 at 11:33

Some data

data = Table[{"string_" <> ToString[i], i}, {i, 1, 10}];


Convert the data involving String into rules using Rule.

rule=(data/.List[a_,b_]-> Rule[b,a])


Arbitrary input data tab given as a list and you obtain the result applying the above rule assignment rule

tab=Table[RandomChoice[Range[10]], {i, 1, 5}, {j, 1, 8}, {k, 1,10}];
tab/. rule


{{{string10,string6,string3,string7,<<3>>,string1,string5,string3},<<7>>},<<4>>}

BR

If your data is stored as:

list = {{"String1", 8}, {"String2", 101}, {"String3", 37}, {"String4",28}}
anotherlist = {{8, 37, 8}, {28}, {28, 101}};


...this will give you your result:

ReplaceAll[anotherlist, MapThread[Rule, Transpose[Map[Reverse, list]]]]
`

output: {{"String1", "String3", "String1"}, {"String4"}, {"String4","String2"}}

Explanation: ReplaceAll replaces his first argument with the rules in the second argument. I think there are several ways to make a list of rules, but i personally find the combination of the functions MapThread and Rule very convenient and easy to use.

• Hmm... I should have checked PlatoManiac's answer before submitting mine...Basically the same method, slightly different notation. – Aart Goossens Nov 5 '12 at 18:05