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?
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]]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With