4
$\begingroup$

For example, I have {{a,b},{c,d},{e,f}} and I want {{a,b,a+b},{c,d,c+d},{e,f,e+f}}. I'm not finding a way to accomplish this.

$\endgroup$
8
$\begingroup$
lst = {{a, b}, {c, d}, {e, f}}
{##, +##} & @@@ lst

{{a, b, a + b}, {c, d, c + d}, {e, f, e + f}}

{##, +##} & @@@ {{a, b}, {x, y, z}, {r, s, t, u}, {w}}

{{a, b, a + b}, {x, y, z, x + y + z}, {r, s, t, u, r + s + t + u}, {w, w}}

$\endgroup$
  • $\begingroup$ Very elegant... and generalizes to sublists of arbitrary length (+1). $\endgroup$ – David G. Stork Feb 16 '18 at 1:12
  • $\begingroup$ Thank you @David. Good point re generalization. $\endgroup$ – kglr Feb 16 '18 at 1:44
  • $\begingroup$ Delicious! (plus filler to get to 15) . $\endgroup$ – Christopher Lamb Feb 16 '18 at 4:01
4
$\begingroup$
Replace[list, {a_, b_} -> {a, b, a + b}, 2]
$\endgroup$
3
$\begingroup$

For example, you can map a function onto each element, like this:

Append[#, Total[#]] & /@ {{a, b}, {c, d}, {e, f}}
(* {{a, b, a + b}, {c, d, c + d}, {e, f, e + f}} *)

Here, the pure function Append[#, Total[#]] & is applied to each sub-list in the list {{a, b}, {c, d}, {e, f}}.

$\endgroup$
2
$\begingroup$

{#[[1]], #[[2]], #[[1]] + #[[2]]} & /@ {{a, b}, {c, d}, {e, f}}

{{a, b, a + b}, {c, d, c + d}, {e, f, e + f}}

$\endgroup$
  • 2
    $\begingroup$ Or this {#1, #2, #1 + #2} & @@@ {{a, b}, {c, d}, {e, f}} $\endgroup$ – Okkes Dulgerci Feb 16 '18 at 1:38
  • 1
    $\begingroup$ Or Flatten[{#, Total@#}] & /@ lst $\endgroup$ – user1066 Feb 16 '18 at 10:56

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.