python count items in list and keep their order of occurrance

后端 未结 3 986
独厮守ぢ
独厮守ぢ 2021-01-19 07:48

Given: a list, such as l=[4,4,4,4,5,5,5,6,7,7,7] Todo: get the count of an element and keep their occurrence order, e.g.: [(4,4),(5,3),(6,1),(7,3)]

I could do it wit

相关标签:
3条回答
  • 2021-01-19 08:26

    If you are using Python 2.7, you can use the Counter from collections, which does exactly what you are looking to do:

    http://docs.python.org/library/collections.html#collections.Counter

    0 讨论(0)
  • 2021-01-19 08:27
    >>> import itertools
    >>> [(k, len(list(g))) for k, g in itertools.groupby(l)]
    [(4, 4), (5, 3), (6, 1), (7, 3)]
    

    This keeps the order of the items and also allows repeated items:

    >>> l=[4,4,4,4,5,5,5,6,7,7,7,4,4,4,4,4]
    >>> [(k, len(list(g))) for k, g in itertools.groupby(l)]
    [(4, 4), (5, 3), (6, 1), (7, 3), (4, 5)]
    
    0 讨论(0)
  • 2021-01-19 08:30

    Use groupby:

    >>> l = [4,4,4,4,5,5,5,6,7,7,7,2,2]
    >>> from itertools import groupby
    >>> [(i, l.count(i)) for i,_ in groupby(l)]
    [(4, 4), (5, 3), (6, 1), (7, 3), (2, 2)]
    
    0 讨论(0)
提交回复
热议问题