Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort like values in Python

Tags:

python

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?

like image 790
Greg Avatar asked Dec 21 '22 18:12

Greg


1 Answers

Use groupby from the itertools module.

from itertools import groupby

L = [2, 2, 3, 4, 4, 10]

L.sort()
for key, iterator in groupby(L):
    print key, list(iterator)

Result:

2 [2, 2]
3 [3]
4 [4, 4]
10 [10]

A couple of things to be aware of: groupby needs 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 store list(iterator) to another list or something. One-liner giving you the result you want:

>>> [list(it) for key, it in groupby(sorted(L))]
[[2, 2], [3], [4, 4], [10]]
like image 168
Lauritz V. Thaulow Avatar answered Dec 23 '22 08:12

Lauritz V. Thaulow