3

Given a list:

>>> l = ['x', 'x', 'y', 'y', 'x']

I could get the count of the list by using collections.Counter:

>>> from collections import Counter
>>> Counter(l)
Counter({'x': 3, 'y': 2})

How can I count contiguous items instead of the global count of the elements in the list? E.g.

>>> l = ['x', 'x', 'y', 'y', 'x']
>>> ContiguousCounter(l)
[('x',2), ('y',2), ('x', 1)]

>>> l = ['x', 'x', 'y', 'y', 'x', 'x', 'x', 'y']
>>> ContiguousCounter(l)
[('x',2), ('y',2), ('x', 3), ('y', 1)]
alvas
  • 115,346
  • 109
  • 446
  • 738

1 Answers1

8

You could use built-in itertools.groupby function:

In [3]: from itertools import groupby

In [4]: l = ['x', 'x', 'y', 'y', 'x']

In [5]: list(groupby(l))
Out[5]: 
[('x', <itertools._grouper at 0x7fd94716f1d0>),
 ('y', <itertools._grouper at 0x7fd94716f208>),
 ('x', <itertools._grouper at 0x7fd94716f240>)]

In [6]: [(x, len(list(g))) for x, g in groupby(l)]
Out[6]: [('x', 2), ('y', 2), ('x', 1)]
awesoon
  • 32,469
  • 11
  • 74
  • 99