在列表中查找ContiguousCount项?

时间:2016-04-21 07:29:35

标签: python list counter contiguous

给出一个清单:

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

我可以使用collections.Counter

获取列表的计数
>>> from collections import Counter
>>> Counter(l)
Counter({'x': 3, 'y': 2})

如何计算连续项目而不是列表中元素的全局计数?例如

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

1 个答案:

答案 0 :(得分:8)

您可以使用内置itertools.groupby功能:

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