How to sort values ​​in Python

I was wondering how to sort the values ​​in a list and then split as values ​​into a sub-list.

For example: I need 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 the sorted api and it works well for sorting things in their own list, but does not break the lists into sub-lists. Which module will help me?

+4
source share
5 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 few things you need to know about: groupby needs the data that it works to be sorted by the same key that you want to group, or it will not work. In addition, the iterator must be consumed before moving on to the next group, so make sure you store list(iterator) in another list or something like that. One-liner gives you the result you want:

 >>> [list(it) for key, it in groupby(sorted(L))] [[2, 2], [3], [4, 4], [10]] 
+5
source

Check the itertools module, it has a useful groupby function:

 import itertools as i for k,g in i.groupby(sorted([2,2,3,4,4,10])): print list(g) .... [2, 2] [3] [4, 4] [10] 

You should be able to change this to get the values ​​in the list.

+2
source

As everyone else suggested itertools.groupby (which would be my first choice) - it is also possible with collections.Counter to get the key and frequency, sort by key, and then expand the freq frequency.

 from itertools import repeat from collections import Counter grouped = [list(repeat(key, freq)) for key, freq in sorted(Counter(L).iteritems())] 
+2
source

itertools.groupby() with full list comprehension.

 In [20]: a = [1, 1, 2, 3, 3, 4, 5, 5, 5, 6] In [21]: [ list(subgroup) for key, subgroup in itertools.groupby(sorted(a)) ] Out[21]: [[1, 1], [2], [3, 3], [4], [5, 5, 5], [6]] 

Note that groupby() returns a list of iterators, and you must consume these iterators in order. According to the docs:

The returned group itself is an iterator that shares the base iterable with groupby (). Since the source is shared when the groupby () object is expanded, the previous group is no longer displayed. Thus, if this data is needed later, it should be saved as a list:

+1
source

If you don't want to use itertools and can wrap your head around list comprehension, this should do the trick too:

 def group(a): a = sorted(a) d = [0] + [x+1 for x in range(len(a)-1) if a[x]!=a[x+1]] + [len(a)] return [a[(d[x]):(d[x+1])] for x in range(len(d)-1)] 

where a is your list

+1
source

All Articles