2016-04-21 9 views
3

eine Liste Gegeben:Suchen ContiguousCount von Elementen in der Liste?

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

Wie kann ich zähle zusammenhängende Elemente statt der globalen Zählung der Elemente in der Liste:

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

ich die Anzahl der in der Liste unter Verwendung collections.Counter bekommen könnte ? Zum Beispiel

>>> 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)] 

Antwort

8

Sie konnten verwenden eingebaute in itertools.groupby Funktion:

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)]