Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 获取最长重复字符串的索引_Python_List - Fatal编程技术网

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来处理类似的事情。非常感谢你的回答!