Python counts items in a list and preserves their order of execution

Given: a list, such as l = [4,4,4,4,5,5,5,6,7,7,7] Todo: get the counter of an element and keep the order in which they appear, for example: [(4,4) , (5.3), (6.1), (7.3)]

I could do it with

tmpL = [(i,l.count(i)) for i in l] tmpS = set() cntList = [x for x in tmpL if x not in tmpS and not tmpS.add(x)] 

But is there a better way? I saw the link here , but sorts the counts and therefore upsets.

Edit: performance is not a problem to solve, preferably something built-in.

+4
source share
3 answers

Use groupby :

 >>> l = [4,4,4,4,5,5,5,6,7,7,7,2,2] >>> from itertools import groupby >>> [(i, l.count(i)) for i,_ in groupby(l)] [(4, 4), (5, 3), (6, 1), (7, 3), (2, 2)] 
+9
source
 >>> import itertools >>> [(k, len(list(g))) for k, g in itertools.groupby(l)] [(4, 4), (5, 3), (6, 1), (7, 3)] 

This preserves the order of the elements, and also allows you to repeat the elements:

 >>> l=[4,4,4,4,5,5,5,6,7,7,7,4,4,4,4,4] >>> [(k, len(list(g))) for k, g in itertools.groupby(l)] [(4, 4), (5, 3), (6, 1), (7, 3), (4, 5)] 
+7
source

If you are using Python 2.7, you can use a count from collections, which does exactly what you are looking for:

http://docs.python.org/library/collections.html#collections.Counter

+2
source

All Articles