开发者

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]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜