Mathematica Asked by J.A on January 10, 2021
If I have a list for example :
{{4,1},{9,2},{16,3},{25,4}}
Is there a command that replaces the first element by its square root and returns a list ? In the example above it would return :
{{2,1},{3,2},{4,3},{5,4}}
(Obviously the list above is short and easy to manipulate, but I’m asking a question for a longer and more complicated one)
MapAt[Sqrt, {{4, 1}, {9, 2}, {16, 3}, {25, 4}}, {All, 1}]
{{2, 1}, {3, 2}, {4, 3}, {5, 4}}
Correct answer by Henrik Schumacher on January 10, 2021
or Map a user defined function down the list:
f[{x_, y_}] := {Sqrt[x], y}
f /@ {{4, 1}, {9, 2}, {16, 3}, {25, 4}}
(* {{2, 1}, {3, 2}, {4, 3}, {5, 4}} *)
Answered by Joe on January 10, 2021
I like to use Replace
whenever possible:
Replace[
{{4, 1}, {9, 2}, {16, 3}, {25, 4}},
{first_, rest__} :> {Sqrt[first], rest},
{1}
]
(* {{2, 1}, {3, 2}, {4, 3}, {5, 4}} *)
Answered by Jason B. on January 10, 2021
{Sqrt[#1], #2} & @@@ {{4, 1}, {9, 2}, {16, 3}, {25, 4}}
{{2, 1}, {3, 2}, {4, 3}, {5, 4}}
And much to my astonishment, using Part
with Map
is faster than the above (0.015 seconds vs 0.060 seconds on list of length 100,000)
{Sqrt[#[[1]]], #[[2]]} & /@ {{4, 1}, {9, 2}, {16, 3}, {25, 4}}
{{2, 1}, {3, 2}, {4, 3}, {5, 4}}
Or, if you felt compelled to use patterns,
{{4, 1}, {9, 2}, {16, 3}, {25, 4}} /. {a_?NumericQ, b_} :> {Sqrt[a], b}
{{2, 1}, {3, 2}, {4, 3}, {5, 4}}
or
Cases[{{4, 1}, {9, 2}, {16, 3}, {25, 4}}, {a_?NumericQ, b_} :> {Sqrt[a], b}]
{{2, 1}, {3, 2}, {4, 3}, {5, 4}}
Answered by NonDairyNeutrino on January 10, 2021
lst = {{4, 1}, {9, 2}, {16, 3}, {25, 4}};
lst[[All, 1]] = Sqrt@lst[[All, 1]];
lst
{{2, 1}, {3, 2}, {4, 3}, {5, 4}}
Also
lst = {{4, 1}, {9, 2}, {16, 3}, {25, 4}};
Transpose[{Sqrt[#[[1]]], #[[2]]}&@Transpose[#]]&@lst
{{2, 1}, {3, 2}, {4, 3}, {5, 4}}
And
lst = {{4, 1}, {9, 2}, {16, 3}, {25, 4}};
lst = ReplacePart[lst, {a_, 1} :> Sqrt[lst[[a, 1]]]]
{{2, 1}, {3, 2}, {4, 3}, {5, 4}}
Answered by kglr on January 10, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP