2
$\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
$\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$
  • $\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 '17 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 '17 at 14:01
  • $\begingroup$ Ah I see, thank you! $\endgroup$ – holistic Aug 17 '17 at 14:05
3
$\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$
  • $\begingroup$ So many solutions, thanks :)! $\endgroup$ – holistic Aug 17 '17 at 14:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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