I was wondering how to sort like values in a list, and then break like values into a sub-list.
For example: I would want a function that probably does something like
def sort_by_like_values(list):
#python magic
>>>list=[2,2,3,4,4,10]
>>>[[2,2],[3],[4,4],[10]]
OR
>>>[2,2],[3],[4,4],[10]
I read up on the sorted api and it works well for sorting things within their own list, but doesn’t break lists up into sub-lists. What module would help me out here?
Use
groupbyfrom the itertools module.Result:
A couple of things to be aware of:
groupbyneeds the data it works on to be sorted by the same key you wish to group by, or it won’t work. Also, the iterator needs to be consumed before continuing to the next group, so make sure you storelist(iterator)to another list or something. One-liner giving you the result you want: