2
$\begingroup$

I have a list of pairs $\{\{a_1,A_1\},\ldots\{a_n,A_n\}\}$. Suppose $A_i=A_j$ for some $i\neq j$. Then I would like to eliminate both $\{a_i,A_i\}$ and $\{a_j,A_j\}$ from this list, and instead of them put $\{a_i+a_j,A_i\}$. How I can do that?

$\endgroup$

4 Answers 4

4
$\begingroup$

Create a testing setup:

SeedRandom[1];
chars = RandomChoice[Alphabet[], 10]
nums = RandomInteger[{1, 9}, 10]
myList = Transpose[{nums, chars}]
{{4, "f"}, {3, "a"}, {3, "h"}, {7, "a"}, {6, "c"}, {5, "d"}, {4, 
  "a"}, {1, "v"}, {5, "a"}, {7, "q"}}

First step is to GatherBy the last entry:

GatherBy[myList, Last]
{{{4, "f"}}, {{3, "a"}, {7, "a"}, {4, "a"}, {5, "a"}}, {{3, 
   "h"}}, {{6, "c"}}, {{5, "d"}}, {{1, "v"}}, {{7, "q"}}}

For each of these sublists, Total the first column and copy last entry of the first item as at least one item is guaranteed to be present in the sublist:

{Plus @@ #[[All, 1]], Last@First@#} & /@ GatherBy[myList, Last]
{{4, "f"}, {19, "a"}, {3, "h"}, {6, "c"}, {5, "d"}, {1, "v"}, {7, 
  "q"}}
$\endgroup$
9
$\begingroup$
myList = {{1, "a"}, {2, "b"}, {4, "a"}};

KeyValueMap[
  {#2, #1}&,
  GroupBy[myList, Last -> First, Total]
]

(* Out: {{5, a}, {2, b}} *)
$\endgroup$
2
$\begingroup$

Okay, if I understood correctly:

myList = {{1, "a"}, {2, "b"}, {4, "a"}};

Now, just find where each a, and b are, and "add" them:

myReducedList = {{Total[#[[1]] & /@ Select[myList, #[[2]] == "a" &]], "a"},
 {Total[#[[1]] & /@ Select[myList, #[[2]] == "b" &]], "b"}}
(*{{5, "a"}, {2, "b"}}*)
$\endgroup$
2
  • 1
    $\begingroup$ It is not like that. For example take a list $((1,a),(2,b),(4,a))$. Then the result should be $((5,a),(2,b))$. $\endgroup$
    – mikis
    Commented May 6, 2022 at 21:56
  • $\begingroup$ @mikis not sure I understand, but maybe my updated version works? $\endgroup$ Commented May 6, 2022 at 22:10
1
$\begingroup$
list = {{1, "a"}, {2, "b"}, {4, "a"}};

Using Merge and MapApply (new in 13.1)

Merge[Total] @ MapApply[#2 -> #1 &] @ list

<|"a" -> 5, "b" -> 2|>

KeyValueMap[Reverse @* List][%]

{{5, "a"}, {2, "b"}}

$\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.