Python: determine length of sequence of equal items in list

后端 未结 2 1041
余生分开走
余生分开走 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:48

    You almost surely want to use itertools.groupby:

    l = [0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,2,2,2]
    answer = []
    for key, iter in itertools.groupby(l):
        answer.append((key, len(list(iter))))
    
    # answer is [(0, 6), (1, 6), (0, 4), (2, 3)]
    

    If you want to make it more memory efficient, yet add more complexity, you can add a length function:

    def length(l):
        if hasattr(l, '__len__'):
            return len(l)
        else:
            i = 0
            for _ in l:
                i += 1
            return i
    
    l = [0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,2,2,2]
    answer = []
    for key, iter in itertools.groupby(l):
        answer.append((key, length(iter)))
    
    # answer is [(0, 6), (1, 6), (0, 4), (2, 3)]
    

    Note though that I have not benchmarked the length() function, and it's quite possible it will slow you down.

提交回复
热议问题