如何计算Python中列表项中单词的连续最大出现次数

2024-09-30 02:21:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试实现一个代码,该代码将计算列表项中单词的最长运行时间

    for_example = ['smaplakidfsmapsmapsmapuarebeautiful']

所以在这个例子中,它将是3,因为smap被重复了3次,所以有一个代码可以为我完成这个任务,不管这个单词是什么


Tags: 代码列表forexample时间单词例子smap
1条回答
网友
1楼 · 发布于 2024-09-30 02:21:04

编辑: 如果您有一个项目列表,可以如下方式调用函数:

[countMaxConsecutiveOccurences(item, 'smap') for item in items]
def countMaxConsecutiveOccurences(item, s):
    i = 0
    n = len(s)
    current_count = 0
    max_count = 0
    while i < len(item):
        if item[i:i+n] == s:
            current_count += 1
            max_count = max(max_count, current_count)
            i += n
        else:
            i += 1
            current_count = 0     
    return max_count

countMaxConsecutiveOccurences('smaplakidfsmapsmapsmapuarebeautiful', 'smap')

相关问题 更多 >

    热门问题