Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.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 一行中有n个相等字符的筛选字符串_Python_String_List_Filter_Char - Fatal编程技术网

Python 一行中有n个相等字符的筛选字符串

Python 一行中有n个相等字符的筛选字符串,python,string,list,filter,char,Python,String,List,Filter,Char,是否有一个选项如何从一行中包含例如3个相等字符的字符串列表中筛选这些字符串?我创建了一个方法,可以做到这一点,但我很好奇,是否有一个更具python风格的方法,或者更有效或更简单的方法来做到这一点 list_of_strings = [] def check_3_in_row(string): for ch in set(string): if ch*3 in string: return True return False new_

是否有一个选项如何从一行中包含例如3个相等字符的字符串列表中筛选这些字符串?我创建了一个方法,可以做到这一点,但我很好奇,是否有一个更具python风格的方法,或者更有效或更简单的方法来做到这一点

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)]
编辑: 我刚刚找到了一个解决方案:

new_list = [x for x in set(keywords) if any(ch*3 in x for ch in x)]

但我不确定哪种方法更快—regexp还是this。

您可以使用正则表达式,如下所示

>>> 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']

在这里,
匹配任何字符,并将其捕获到组中(
()
)。我们检查同一个捕获的字符(我们使用backreference
\1
引用字符串中第一个捕获的组)是否还会出现两次(
{2}
表示两次)。

相关:感谢您的回答。很好的解决方案。我已经找到了一种方法——我编辑了我的帖子。@millan您可以使用
timeit
模块进行检查。但是RegEx版本可能比
any
版本更好。我的猜测是,如果字符串长,RegEx会更快,因为它只扫描每个字符串一次,而
any()
方法会扫描n个长度的字符串n次。OTOH,如果列表中的大多数字符串确实包含一组3,并且该组往往出现在字符串的开头附近,那么
any()
方法可能会更快。