Find maximum length of consecutive repeated numbers in a list

前端 未结 2 615
感动是毒
感动是毒 2021-01-14 23:23

My question is how to find the maximum length of consecutive repeated numbers (or elements in general) in a list. I wrote the following function which works fine but I was w

2条回答
  •  逝去的感伤
    2021-01-15 00:01

    You can use itertools.

    In [8]: import itertools
    
    In [9]: z = [(x[0], len(list(x[1]))) for x in itertools.groupby(a)]
    
    In [10]: z
    Out[10]: [(1, 2), (2, 3), (3, 1)]
    

    Tuples are in (item, count) format. If there are multiple runs of a given number, this will group them accordingly as well. See below.

    In [11]: a = [1,1,1,1,1,2,2,2,2,2,1,1,1,3,3]
    
    In [12]: z = [(x[0], len(list(x[1]))) for x in itertools.groupby(a)]
    
    In [13]: z
    Out[13]: [(1, 5), (2, 5), (1, 3), (3, 2)]
    

    Getting the max value isn't that hard from here.

    In [15]: max(z, key=lambda x:x[1])[1]
    Out[15]: 5
    

提交回复
热议问题