在整数列表中找到最长的0序列 [英] Find longest sequence of 0's in the integer list
问题描述
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代码帮助.
Return initial and ending index of longest sequence of 0
's in the list.
As, longest sequence of 0
's in above list is 0,0,0,0,0,0,0,0
so it should return 12,19
as starting and ending index.Please help with some one line python code.
我尝试过:
k = max(len(list(y)) for (c,y) in itertools.groupby(A) if c==0)
print(k)
,它返回8
作为最大长度.
which return 8
as the max length.
现在,如何找到最长序列的开始和结束索引?
Now, how to find start and end index of longest sequence?
推荐答案
您可以首先使用enumerate
将带有索引的项目压缩,
you can first use enumerate
to zip the item with index,
然后itertools.groupby(list,operator.itemgetter(1))
按项目分组
仅使用list(y) for (x,y) in list if x == 0
过滤0
,
,最后是max(list, key=len)
,以获得最长的序列.
and at last max(list, key=len)
to get the longest sequence.
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
这篇关于在整数列表中找到最长的0序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!