6
$\begingroup$

I have the list:

List1={{7, {-0.91, {a -> 0.61}}}, {10, {-1.41, {a ->
     0.44}}}, {12, {-2.00, {a ->
     0.35}}}, {15, {-2.69, {a -> 0.28}}}}

I would like to multiply the numbers -0.91, -1.41, -2.00, -2.69 by 5 and write them into the following list:

List2={{7, -0.91*5}, {10,-1.41*5}, {12, -2.00*5}, {15, -2.69*5}}

How can I do it without a lot of loops?

$\endgroup$
1
  • 6
    $\begingroup$ Transpose[{List1[[All, 1]], 5 List1[[All, 2, 1]]}] $\endgroup$
    – Domen
    Commented Dec 21, 2022 at 21:00

5 Answers 5

7
$\begingroup$

All answers are fine and upvoted. I am leaving another approach here -which also seems the simplest so far in my eyes

List1 /. {i_, {j_, k_}} :> {i, 5*j}

list

$\endgroup$
4
  • 1
    $\begingroup$ (+1) Hi, friend! For me, your answer is the best :-) $\endgroup$ Commented Dec 22, 2022 at 1:42
  • 1
    $\begingroup$ @E.Chan-López hey mate. Thanks a lot! You make me blush :-) $\endgroup$
    – bmf
    Commented Dec 22, 2022 at 1:59
  • 3
    $\begingroup$ Nitpick: If List1 has length 2, then this does the wrong thing. Replace[List1,{i_,{j_,_}}:>{i,5*j},{1}] should work. $\endgroup$
    – user293787
    Commented Dec 22, 2022 at 4:54
  • 1
    $\begingroup$ @user293787 yes, that's a good point. Thanks for bringing it up :-) $\endgroup$
    – bmf
    Commented Dec 22, 2022 at 5:11
6
$\begingroup$
Transpose[MapAt[5*# &, Extract[List1, {{All, 1}, {All, 2, 1}}], 2]]

Or

SubsetMap[5*# &, Extract[#, {{1}, {2, 1}}] & /@ List1, {All, 2}]
$\endgroup$
6
$\begingroup$

Try this:

{First[#], Times[Last[#], 5]} & /@ (Most[#] & /@ (Flatten[#, 2] & /@ list1))

Or using Take:

Take[{#[[1]], 5*#[[2]]}, {1, 2}] & /@ Flatten /@ list1
$\endgroup$
1
$\begingroup$
list = 
 {{ 7, {-0.91, {a -> 0.61}}}, 
  {10, {-1.41, {a -> 0.44}}}, 
  {12, {-2.00, {a -> 0.35}}}, 
  {15, {-2.69, {a -> 0.28}}}};

Using Cases

Cases[list, {a_, {b_, _}} :> {a, 5 b}]

{{7, -4.55}, {10, -7.05}, {12, -10.}, {15, -13.45}}

Using MapAt and Splice (new in 12.1)

MapAt[Splice[5 #] &, {;; , 2}] @ MapAt[Nothing &, list, {;; , 2, 2}]

{{7, -4.55}, {10, -7.05}, {12, -10.}, {15, -13.45}}

$\endgroup$
1
$\begingroup$
list = 
 {{ 7, {-0.91, {a -> 0.61}}}, 
  {10, {-1.41, {a -> 0.44}}}, 
  {12, {-2.00, {a -> 0.35}}}, 
  {15, {-2.69, {a -> 0.28}}}};

Taking the pattern used by my mates @bmf and @eldo, and using ReplaceList:

ReplaceList[list, {___, {a_, {b_, _}}, ___} :> {a, 5  b}]

{{7, -4.55}, {10, -7.05}, {12, -10.}, {15, -13.45}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.