简体   繁体   中英

Finding the most consecutive sequence of any item of a list in Python

How can I find the most consecutive sequence of any item(integers) of a list in Python?

my_list = [1, 3, 2, 2, 4, 5, 5, 5, 5, 6, 1, 5, 5]

I want to extract [5, 5, 5, 5] from the list.

NB Please, correct me if I've written anything wrong. :-)

Use itertools.groupby() and max() :

In [1]: my_list = [1, 3, 2, 2, 4, 5, 5, 5, 5, 6, 1, 5, 5]

In [2]: from itertools import groupby

In [4]: max([list(g) for _, g in groupby(my_list)], key=len)
Out[4]: [5, 5, 5, 5]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM