5
$\begingroup$

How can I create list2 from list1?

   list1 = {{a, {a1, a2, a3}}, {b, {b1, b2, b3}}, {c, {c1, c2, c3}}}
   list2 = {{a*4, {a1, a2, a3}}, {b*4, {b1, b2, b3}}, {c*4, {c1, c2, 
    c3}}}

Thank you

$\endgroup$
5

5 Answers 5

6
$\begingroup$

Also

ReplaceAt[list1, x_:> 4 x, {All,1}]

(* {{4 a, {a1, a2, a3}}, {4 b, {b1, b2, b3}}, {4 c, {c1, c2, c3}}} *)

(2)

In addition, it has been shown by Sjoerd Smit that a function may be applied to a matrix column using Query

Query[All, {1 -> (4 #&)}]@list1

(* {{4 a, {a1, a2, a3}}, {4 b, {b1, b2, b3}}, {4 c, {c1, c2, c3}}} *)

In this case, Query apparently uses MapAt 'in the background'

Query[All, {1 -> (4 #&)}]//Normal

(* MapAt[4 #1 & , {All, 1}] *)

(The use of MapAt has been suggested by platomaniac in a comment)

$\endgroup$
6
$\begingroup$

Another way using Part:

{4*#[[1]], #[[2]]} & /@ list1

(*{{4 a, {a1, a2, a3}}, {4 b, {b1, b2, b3}}, {4 c, {c1, c2, c3}}}*)

Also:

Function[{x}, Transpose@{4 x[[All, 1]], x[[All, 2]]}]@list1
(*{{4 a, {a1, a2, a3}}, {4 b, {b1, b2, b3}}, {4 c, {c1, c2, c3}}}*)
$\endgroup$
6
$\begingroup$

1. SubsetMap

list2 = SubsetMap[4 # &, {All, 1}]@list1
{{4 a, {a1, a2, a3}}, {4 b, {b1, b2, b3}}, {4 c, {c1, c2, c3}}}

2. ApplyTo (//=)

list2 = list1;
list2[[All, 1]] //= 4 # &;
list2
 {{4 a, {a1, a2, a3}}, {4 b, {b1, b2, b3}}, {4 c, {c1, c2, c3}}}

3. TimesBy (*=)

list2 = list1;
list2[[All, 1]] *= 4;
list2
{{4 a, {a1, a2, a3}}, {4 b, {b1, b2, b3}}, {4 c, {c1, c2, c3}}}

4. MapApply (@@@)

list2 = {4 #, ##2} & @@@ list1
{{4 a, {a1, a2, a3}}, {4 b, {b1, b2, b3}}, {4 c, {c1, c2, c3}}}
$\endgroup$
3
$\begingroup$
list1 = {{a, {a1, a2, a3}}, {b, {b1, b2, b3}}, {c, {c1, c2, c3}}}

{4, 1} # & /@ list1

MapThread[Times, {Table[{4, 1}, Length@list1], list1}]

Inner[Times, list1, {4, 1}, List]

Inner[Times, {4, 1}, #, List] & /@ list1

{{4 a, {a1, a2, a3}}, {4 b, {b1, b2, b3}}, {4 c, {c1, c2, c3}}}

$\endgroup$
3
$\begingroup$
list = {{a, {a1, a2, a3}}, {b, {b1, b2, b3}}, {c, {c1, c2, c3}}};

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

MapAt[4 # &, {All, 1}] @ list

SequenceReplace[list, {{a_, b_}} :> {4 a, b}]

All return

{{4 a, {a1, a2, a3}}, {4 b, {b1, b2, b3}}, {4 c, {c1, c2, c3}}}

$\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.