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

前端 未结 4 1820
面向向阳花
面向向阳花 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条回答
  •  Happy的楠姐
    2020-12-10 20:36

    Without importing any packages:

    • Build a dictionary and then get the values to a list
      • Use .get to determine if a key exists, and return some specified value, None in this case, if the key is nonexistent.
      • dict.get defaults to None, so this method never raises a KeyError.
        • If None is a value in the dictionary, then change the default value returned by .get.
          • test.get(t[0], 'something here')
    • Because: sub-lists based on common first items.
      • Add index 0 as the key, and then add the list, t, as the dict value.
    test = dict()
    for t in mylist:
        if test.get(t[0]) == None:
            test[t[0]] = [t]
        else:
            test[t[0]].append(t)
            
    final = list(test.values())
    
    # print final results in
    
    [[['AB001', 22100], ['AB001', 32935], ['AB001', 34439]],
     [['XC013', 99834], ['XC013', 86701]],
     [['VD126', 18884]]]
    

提交回复
热议问题