0

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.

5
  • What is the data structure you expect to get? because what you asked is not a valid one. Commented Oct 21, 2018 at 9:27
  • 1
    It should have been {'down' : 3, 'up' : 1, 'right' : 2, 'down' : 2} right? Like a Hashmap in java Commented Oct 21, 2018 at 9:28
  • 1
    Still not valid, you can't have 'down' twice in a dict Commented Oct 21, 2018 at 9:31
  • @MaorRefaeli sorry, I hope that it's good now with using a tuple. Commented Oct 21, 2018 at 9:32
  • 1
    List of tuples is a better data structure for your implementation Commented Oct 21, 2018 at 9:34

2 Answers 2

3

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)]
Sign up to request clarification or add additional context in comments.

Comments

1

Try This:

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

2 Comments

could you please elaborate as to have that solution works?
groupby gives group of same element like: [('down', <itertools._grouper at 0x7f4438b1b320>), ('up', <itertools._grouper at 0x7f4438b1b6d8>), ('right', <itertools._grouper at 0x7f4438b1b5f8>), ('down', <itertools._grouper at 0x7f4438b1b278>)] So for each print the element and length of group.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.