# Splitting list into sublists based off string value [duplicate]

I'm new to Mathematica so please bare with me!

I wish to split an imported data list off of {x,y} values based off the y value, and then sum the corresponding parts.

An example of the imported list:

MyDataList = {{{20, "a"}, {3, "a"}, {4,"a"}, {6, "b"}, {10, "a"}, {12, "b"}, {2, "a"}}}


I want to make 2 sublists e.g.:

AList = {{20, "a"}, {3, "a"}, {4,"a"},{10, "a"},{2, "a"}}
BList = {{6,"b"},{12,"b"}}


And then sum the numerical parts of the list, e.g.:

AList = 39
Blist = 18


I've tried GatherBy and SplitBy to try and partition but it doesn't quite split how I need. Any advice would be super helpful!

You can use GroupBy. Note GroupBy returns an Association.

With

myDataList = {{{20, "a"}, {3, "a"}, {4, "a"}, {6, "b"}, {10, "a"}, {12, "b"}, {2, "a"}}};


Then

res = GroupBy[First@myDataList, Last -> First, Total]

<|"a" -> 39, "b" -> 18|>


and

res["a"]

39


Hope this helps.

Your list is wrapped in another list, so you can use First to remove the outer list.

{AList, BList} = GatherBy[First@MyDataList, Last];

Total[First /@ AList]
(* 39 *)

Total[First /@ BList]
(* 18 *)

• Hi, when I try that it returns, Lists {Alist,Blist} and {MyDataList} are not the same shape? Mar 20, 2023 at 20:52
• Then you must have changed something in your code. I used exactly the same MyDataList as you provided in the question, and it should work. Mar 20, 2023 at 21:24

Using Reap/Sow:

Last@Reap@Scan[Sow[First@#, Last@#] &, MyDataList, {2}] // Map[Total]


Using Merge:

Rule @@@ (Reverse /@ First@MyDataList) // Merge[#, Total] & // Values


Result:

{39, 18}