Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do operations for the second component of each element in a list in Mathematica

I can use the following way to do some operation (in this case ToString) for the first component of each element in a list:

{ToString@#[[1]], Rest@#}~Flatten~1 & /@ {{1, 2}, {3, 4, 5}}

However, I have a few questions:

  • It does not work for {ToString@#[[1]], Rest@#}~Flatten~1 & /@ {{1, 2}, 2, {3, 4, 5}} for obvious reason. How to make it also work in this case? The expected output would be {{"1", 2}, 2, {"3", 4, 5}}.
  • How to do this for the second(or third, etc.) component easily? I.e. I want the output to be {{0}, {1, "2"}, {3, "4", 5}, {6, "7", 9, 10}}
  • Is there a way to use pattern/rule (like /.{#[[1]]->ToString[#[[1]]]}) for this kind of operation? So please list all solutions you may think of regardless of the efficiency.

Thanks a lot!

like image 810
Qiang Li Avatar asked Dec 17 '22 05:12

Qiang Li


1 Answers

I didn't realize this was the same as Leonid's core function until I had written it. Still perhaps that says that this may be a little more transparent than his rather elaborate function.

lst = {{1, 2}, 2, {3, 4, 5}};

Replace[lst, {a_, b__} :> {ToString@a, b}, 1]
{{"1", 2}, 2, {"3", 4, 5}}

One can then use {x:Repeated[_, {4}], a_, b__} :> {x, ToString@a, b}, 1] for the fifth index, etc.

like image 184
Mr.Wizard Avatar answered May 23 '23 04:05

Mr.Wizard