python - 如何停止对字符串列表中重复字母的过度计数

标签 python string list

我正在尝试计算重复字母在列表元素中出现的次数。

例如,给定

arr = ['capps','hat','haaah']

我列出了一个列表,然后得到['1','0','1']

def myfunc(words):
    counter = 0 #counters dup letters in words
    len_ = len(words)-1
    for i in range(len_):
        if words[i] == words[i+1]: #if the letter ahead is the same add one
            counter+=1
    return counter

def minimalOperations(arr):
     return [*map(myfunc,arr)] #map fuc applies myfunc to element in words.

但是我的代码会输出 [1,0,2]

我不知道为什么我计算过多了。 谁能帮我解决这个问题,先谢谢了。

最佳答案

使用正则表达式的更有效的解决方案:

import re

def myfunc(words):
    reg_str = r"(\w)\1{1,}"
    return len(re.findall(reg_str, words))

该函数将查找长度为 2 或以上且包含相同字母的子字符串的数量。因此,示例中的“aaa”只会被计算一次。

对于像

这样的字符串
'hhhhfafaahggaa'

输出将为 4 ,因为同一字母的最大子串至少出现两次: 'hhh' 、 'ss' 、 'gg' 、 'aa'

关于python - 如何停止对字符串列表中重复字母的过度计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51845080/

相关文章:

python - 如何在 numpy python3+ 中为数组列表创建 dtype

python - 加快 ~50GB CSV 文件的轻处理

python - Keras:处理自定义 PIL 逊相关指标的批量大小维度

python - 为什么 np.ndarray.__deepcopy__ 需要一个多余的参数?

c++ - 'to_string' 未知覆盖说明符

Java输入失败

python - 基于公共(public)元组元素组合元组列表

list - 如何遍历列表并在Dart中重置?

java - Jsoup 获取值 =""中的元素

python - 如何将多个元素插入到列表中?