在整数列表中找到最长的0序列


问题内容

A = [1,2,0,0,3,4,5,-1,0,2,-1,-3,0,0,0,0,0,0,0,0,-2,-3,-4,-5,0,0,0]

返回0列表中最长序列的起始索引和终止索引。因为,0上面列表中的的最长序列是0,0,0,0,0,0,0,0所以它应该12,19作为开始和结束索引返回。请帮助一些Python代码。

我试过了 :

k = max(len(list(y)) for (c,y) in itertools.groupby(A) if c==0)
print(k)

返回8最大长度。

现在,如何找到最长序列的开始和结束索引?


问题答案:

您可以先使用enumeratezip压缩带有索引的项目,

然后itertools.groupby(list,operator.itemgetter(1))按项目分组

0使用过滤list(y) for (x,y) in list if x == 0

最后max(list, key=len)得到最长的序列。

import itertools,operator
r = max((list(y) for (x,y) in itertools.groupby((enumerate(A)),operator.itemgetter(1)) if x == 0), key=len)
print(r[0][0]) # prints 12
print(r[-1][0]) # prints 19