我有一个数字列表:
a=[2,3,4,5,1,3,2,4,5,6,2,6,7,5,2,7,5,6,2]
我想要最长的不包含2的序列,所以答案是:
[3,4,5,1,3]
我怎么能在python中这样做? 谢谢你的帮助,
答案 0 :(得分:3)
您可以使用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))
打印
[3, 4, 5, 1, 3]