Python 获取最长重复字符串的索引
我有以下清单:Python 获取最长重复字符串的索引,python,list,Python,List,我有以下清单: l = [True, True, False, True, True, True, False, False] 如何获取最长重复子字符串的索引True 输出将是:[3,4,5] 这就是我尝试过的: get_index=[] counter = 0 for i,li in enumerate(l): if li == True: counter = counter +1 get_index.append([i,counter]) e
l = [True, True, False, True, True, True, False, False]
如何获取最长重复子字符串的索引True
输出将是:[3,4,5]
这就是我尝试过的:
get_index=[]
counter = 0
for i,li in enumerate(l):
if li == True:
counter = counter +1
get_index.append([i,counter])
else:
counter = 0
我得到了这样一个列表:[[0,1],[1,2],[3,1],[4,2],[5,3]]
现在的想法是只保留左侧数字不断增加的配对(即3,4,5),并且最后一个右侧数字在所有配对中得分最高…但我不知道怎么做?试试这个:
clusters = [[]]
for index, b in enumerate(l):
if b:
# Append to the existing cluster if this item is True
clusters[-1].append(index)
elif clusters[-1]:
# If this item is False, finalize the previous cluster and init
# a new empty one (but don't bother if the previous cluster was
# already empty)
clusters.append([])
# Print the longest cluster
print(max(clusters, key=len))
您应该知道,StackOverflow不是一个代码编写服务,所以请编辑您试图在问题中写入的代码。@barny会的。不必告诉您。我不理解输出以及它与真-假序列的关系。我看到2个“正确”或3个“正确”。甚至索引也不匹配。@barny请看一下我更新的问题。谢谢。:)不需要在这里创建lambda,您可以传递
key=len
这是真的,谢谢!我已经习惯了自动使用lambdas来处理类似的事情。非常感谢你的回答!