Python how to count groups of duplicates?

I'm new to python and the problem I'm facing is how can I count groups of duplicates. For example given a list like this:

['down', 'down', 'down', 'up', 'right', 'right', 'down', 'down']

I have to calculate the following:

[('down', 3), ('up', 1), ('right', 2), ('down', 2)]

Or rather how can I achieve this in a pythonic way coming from languages like java/c#?

EDIT: Since it seems that I didn't clarify my my problem enough, I don't want to count all the occurrences of for example down in the list, but only those that are neighbors (if that is the correct phrasing), so Counter(my_list) doesn't give the desired output.

Upvotes: 0

Views: 68

Answers (2)

Rohit-Pandey
Rohit-Pandey

Reputation: 2159

Try This:

from itertools import groupby
[(c,len(list(cgen))) for c,cgen in groupby(a)]

Upvotes: 1

Aran-Fey
Aran-Fey

Reputation: 43166

Use itertools.groupby:

>>> import itertools
>>> lst = ['down', 'down', 'down', 'up', 'right', 'right', 'down', 'down']
>>> [(value, sum(1 for _ in group)) for value, group in itertools.groupby(lst)]
[('down', 3), ('up', 1), ('right', 2), ('down', 2)]

Upvotes: 3

Related Questions