首页 > 解决方案 > 如何计算Python中列表项中单词的连续最大出现次数

问题描述

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

    for_example = ['smaplakidfsmapsmapsmapuarebeautiful']

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

标签: pythonpython-3.xlistcountcounter

解决方案


编辑: 如果你有一个项目列表,你可以这样调用函数:

[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')

推荐阅读