Python: determine length of sequence of equal items in list

后端 未结 2 1047
余生分开走
余生分开走 2020-12-18 02:05

I have a list as follows:

l = [0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,2,2,2]

I want to determine the length of a sequence of equal items, i.e for

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-18 02:52

    Mike's answer is good, but the itertools._grouper returned by groupby will never have a __len__ method so there is no point testing for it

    I use sum(1 for _ in i) to get the length of the itertools._grouper

    >>> import itertools as it
    >>> L = [0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,2,2,2]
    >>> [(k, sum(1 for _ in i)) for k, i in it.groupby(L)]
    [(0, 6), (1, 6), (0, 4), (2, 3)]
    

提交回复
热议问题