Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting sub-lists into new sub-lists based on common first items

I have a large number of two-membered sub-lists that are members of a list called mylist:

mylist = [['AB001', 22100],
          ['AB001', 32935],
          ['XC013', 99834],
          ['VD126', 18884],
          ['AB001', 34439],
          ['XC013', 86701]]

I want to sort mylist into new sub-lists based on whether the sub-lists contain the same string as the first item. For example, this is what I am looking for my code to output:

newlist = [['AB001', 22100], ['AB001', 32935], ['AB001', 34439]],
          [['XC013', 99834], ['XC013', 86701]],
          [['VD126', 18884]]

Here is how I was trying to code this:

mylist = sorted(mylist)
newlist = []
for sublist in mylist:
    id = sublist[0]
if id == next.id:
    newlist.append(id)
print newlist

I was also trying to understand if itertools.groupby() was the correct tool for this problem. Can someone help me with this problem?

like image 334
drbunsen Avatar asked Dec 22 '22 09:12

drbunsen


1 Answers

You were right about this being a job for groupby:

from itertools import groupby
from operator import itemgetter

mylist = [['AB001', 22100],
          ['AB001', 32935],
          ['XC013', 99834],
          ['VD126', 18884],
          ['AB001', 4439],
          ['XC013', 86701]]

print([list(value) for key, value in groupby(sorted(mylist), key=itemgetter(0))])

This will give you a list-of-lists, grouped by the first item in the sublist.

[[['AB001', 4439], ['AB001', 22100], ['AB001', 32935]], 
 [['VD126', 18884]], 
 [['XC013', 86701], ['XC013', 99834]]]
like image 126
agf Avatar answered Dec 24 '22 03:12

agf