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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…