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

前端 未结 4 1822
面向向阳花
面向向阳花 2020-12-10 19:49

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

mylist = [[\'AB001\', 22100],
          [\'AB001\', 32         


        
4条回答
  •  庸人自扰
    2020-12-10 20:53

    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]]]
    

提交回复
热议问题