I have a large number of two-membered sub-lists that are members of a list called mylist
:
mylist = [[\'AB001\', 22100],
[\'AB001\', 32
An itertools.groupby
solution will incur O(n log n) cost since the input must be sorted first. You can a use defaultdict
of lists for a guaranteed O(n) solution:
from collections import defaultdict
dd = defaultdict(list)
for item in mylist:
dd[item[0]].append(item)
res = list(dd.values())
print(res)
[[['AB001', 22100], ['AB001', 32935], ['AB001', 34439]],
[['XC013', 99834], ['XC013', 86701]],
[['VD126', 18884]]]