Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python count items in list and keep their order of occurrance

Tags:

python

Given: a list, such as l=[4,4,4,4,5,5,5,6,7,7,7] Todo: get the count of an element and keep their occurrence order, e.g.: [(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 have seen the link here, but it sorts the counts and hence breaks the order.

Edit: performance is not an issue for the solution, preferable something built-in.

like image 296
lukmac Avatar asked Nov 30 '22 07:11

lukmac


2 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)]
like image 195
jro Avatar answered Dec 05 '22 17:12

jro


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

This keeps the order of the items and also allows repeated items:

>>> 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)]
like image 39
Tim Pietzcker Avatar answered Dec 05 '22 17:12

Tim Pietzcker