3
$\begingroup$

Sorry, for the broad title, didn't know how to best describe it. I have a list likes this:

list = {{{1, 2, 3, {4, 5, 6}}, {1, 2, 3, {4, 5, 6}}}, {{1, 2, 
    3, {4, 5, 6}}, {1, 2, 3, {4, 5, 6}}}}

And I want to replace the second part of the list elements, i.e. {4,5,6} everywhere by just the first element of this part, i.e. 4. the list should then look like this:

list2 = {{{1, 2, 3, 4}, {1, 2, 3, 4}}, {{1, 2, 3, 4}, {1, 2, 3, 4}}}

I can do it with some complicated constructions looping through all the list elements by means of Table but there must be an easier way by using Replace or MapAtand I just can't figure it out.

Any help appreciated!

$\endgroup$

4 Answers 4

5
$\begingroup$
list2 = Replace[list, {a_, ___} -> a, {3}]
list2 = MapAt[First, list, {All, All, -1}]

{{{1, 2, 3, 4}, {1, 2, 3, 4}}, {{1, 2, 3, 4}, {1, 2, 3, 4}}}

If list is very big I think the fastest one would be

Join[Drop[list, None, None, -1], list[[All, All, {-1}, 1]], 3]
$\endgroup$
3
  • $\begingroup$ Thanks Coolwater! Can you maybe comment on the first line that uses Replace a bit, I don't understand what exactly you did there ;). Especially this part {a_, ___}->a $\endgroup$
    – holistic
    Aug 17, 2017 at 13:45
  • 1
    $\begingroup$ In the deepest level {3} we need to replace elements with the form {__} (i.e. a list with one or more elements). I write instead {a_, ___} (one element plus zero or more elements) to keep a reference only to what's needed $\endgroup$
    – Coolwater
    Aug 17, 2017 at 14:01
  • $\begingroup$ Ah I see, thank you! $\endgroup$
    – holistic
    Aug 17, 2017 at 14:05
4
$\begingroup$

Also:

ClearAll[f1, f2, f3, ☺]
f1 = ReplacePart[#, {_, _, -1, 0} :> (# &)] &;
f2 = Module[{l = #}, l[[All, All, -1, 0]] = # &; l] &;
f3 = Module[{l = #}, l[[All, All, -1]] = l[[All, All, -1, 1]]; l] &;
☺ = # & @@@ {##} & @@@ # & /@ # &;   (* for fun *)

f1 @ list

{{{1, 2, 3, 4}, {1, 2, 3, 4}}, {{1, 2, 3, 4}, {1, 2, 3, 4}}}

Equal @@ (#@list & /@ {f1, f2, f3, ☺})

True

$\endgroup$
1
  • $\begingroup$ So many solutions, thanks :)! $\endgroup$
    – holistic
    Aug 17, 2017 at 14:44
2
$\begingroup$
Clear["Global`*"];

With another similar entry added at level 1 as an example:

list = {{{1, 2, 3, {4, 5, 6}}, {1, 2, 3, {4, 5, 6}}}, {{1, 2, 
    3, {4, 5, 6}}, {1, 2, 3, {4, 5, 6}}}, {1, 2, 3, {4, 5, 6}}}

Replace[list, {x__Integer, k : {y__}} :> {x, First@k}, -1]

or:

list /. {x__Integer, k : {y__}} :> {x, First@k}

{{{1, 2, 3, 4}, {1, 2, 3, 4}}, {{1, 2, 3, 4}, {1, 2, 3, 4}}, {1, 2, 3, 4}}

$\endgroup$
2
$\begingroup$

Using Map and AtomQ:

Map[If[AtomQ[#], #, ##[[1]]] &, list, {3}]

(*{{{1, 2, 3, 4}, {1, 2, 3, 4}}, {{1, 2, 3, 4}, {1, 2, 3, 4}}}*)
$\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.