过滤字符串中有n个相等字符的字符串

Mil*_*ano 6 python string list filter char

是否有一个选项如何从一行中包含例如3个相等字符的字符串列表中过滤这些字符串?我创建了一个可以做到这一点的方法,但我很好奇是否有更多的pythonic方式或更高效或更简单的方法来做到这一点.

list_of_strings = []


def check_3_in_row(string):
    for ch in set(string):
        if ch*3 in string:
            return True
    return False

new_list = [x for x in list_of_strings if check_3_in_row(x)]
Run Code Online (Sandbox Code Playgroud)

编辑:我刚刚找到一个解决方案:

new_list = [x for x in set(keywords) if any(ch*3 in x for ch in x)]
Run Code Online (Sandbox Code Playgroud)

但我不确定哪种方式更快 - regexp或者这个.

the*_*eye 6

您可以像这样使用正则表达式

>>> list_of_strings = ["aaa", "dasdas", "aaafff", "afff", "abbbc"]
>>> [x for x in list_of_strings if re.search(r'(.)\1{2}', x)]
['aaa', 'aaafff', 'afff', 'abbbc']
Run Code Online (Sandbox Code Playgroud)

在这里,.匹配任何字符,并在组((.))中捕获它.我们检查相同的捕获字符(我们使用反向引用引用\1字符串中的第一个捕获的组)是否出现两次({2}意味着两次).