[英]Finding ContiguousCount of items in list?
給出一個清單:
>>> 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)]
你可以使用內置的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)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.