print the longest sequence of number in number list (python)
I have a list of number:
a=[2,3,4,5,1,3,2,4,5,6,2,6,7,5,2,7,5,6,2]
I want the longest sequence that not contain 2, so the answer is:
[3,4,开发者_运维问答5,1,3]
How can I do this in python? Thanks for helping me,
You can use itertools.groupby()
:
from itertools import groupby
a = [2, 3, 4, 5, 1, 3, 2, 4, 5, 6, 2, 6, 7, 5, 2, 7, 5, 6, 2]
# get the subsequences not containing 2
subsequences = (list(it)
for contains_two, it in groupby(a, lambda x: x == 2)
if not contains_two)
# find the longest one among them
print(max(subsequences, key=len))
prints
[3, 4, 5, 1, 3]
精彩评论