How can I add the elements in the sublists?
For example, if I have the list which is
m={{1,3},{2,3},{4,1}}
then, the output that I want is 3+3+1=10
.
How can I do this?
I thinks the cleanest way is:
Total@m[[All, 2]]
using Esc[[Esc and Esc]]Esc.
If you use it a lot (like me), you can create shortcuts as explained here.
Esc
every time for Part
brackets
$\endgroup$
Following @b.gatessucks
Total[m[[;; , 2]]]
(* 7 *)
If you want to sum all components (as @image_doctor pointed out too, sorry I missed that)
Plus @@@ Transpose[m]
(* 7 7 *)
Total[m[[All , 2]]]
works as well. :)
$\endgroup$
Commented
Oct 30, 2012 at 12:05
Last@Total[{{1, 3}, {2, 3}, {4, 1}}]
or
Total[{{1, 3}, {2, 3}, {4, 1}}]
for both components
{{1, 3}, {2, 3}, {4, 1}} // Query[Total, 2]
7
Unfortunately the current Query
and associated Dataset
implementation is riddled with workarounds - this is going to tech support >>
{{1, 3}, {2, 3}, {4, 1}} // Query[Total, 2] // Trace // LeafCount
3175
Anyone interested in a timing study?
{{1, 3}, {2, 3}, {4, 1}} // Query[Total, 2] // Trace // LeafCount
results in 697
as of May 2023.
$\endgroup$
Just For fun.
m = {{1, 3}, {2, 3}, {4, 1}}; Last[Total[m]]
Part
to get the elements from the list, thenTotal
to sum them up. $\endgroup$Plus @@@ (m\[Transpose])
will give you a list of the sums of the various elements of your list. $\endgroup$