2
$\begingroup$

I have a list like this {{a,10},{b,5},{a,5},{b,1}}. How to get the result {a,15},{b,6}.

$\endgroup$
4
$\begingroup$

Use GroupBy

List @@@ Normal[GroupBy[{{a, 10}, {b, 5}, {a, 5}, {b, 1}}, First -> Last, Total]]
{{a, 15}, {b, 6}}

Without associations:

Transpose[{#[[All, 1, 1]], Total[#[[All, All, 2]], {2}]}] &[
  GatherBy[{{a, 10}, {b, 5}, {a, 5}, {b, 1}}, First]]
| improve this answer | |
$\endgroup$
  • $\begingroup$ thank you! it works. Do you have another solution which doesn't use "association"? $\endgroup$ – Nam Nguyen Jan 9 '18 at 15:36
  • 1
    $\begingroup$ @ERT Yes but i think the association one is faster for large lists $\endgroup$ – Coolwater Jan 9 '18 at 15:39
  • $\begingroup$ Wonderful! Yes, Association is faster. However, I didn't master the concept of Association yet. Thank you very much. You save me a lot of time. I'm an old-school list-manipulation Mathematica. $\endgroup$ – Nam Nguyen Jan 9 '18 at 15:45
  • $\begingroup$ @ERT As a first approximation you can think of an Association as a list which uses (almost) arbritrary expressions for indexing. $\endgroup$ – Henrik Schumacher Jan 9 '18 at 16:31
1
$\begingroup$

Just another way:

lst = {{a, 10}, {b, 5}, {a, 5}, {b, 1}};
Reap[Sow[#2, #1] & @@@ lst, _, {#1, Total@#2} &][[-1]]

yields:

{{a, 15}, {b, 6}}
| improve this answer | |
$\endgroup$
1
$\begingroup$
lst = {{a, 10}, {b, 5}, {a, 5}, {b, 1}} ;

Merge[Total][Rule @@@ lst] // KeyValueMap[List]

{{a, 15}, {b, 6}}

| improve this answer | |
$\endgroup$

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.