【问题标题】:Filter strings where there are n equal characters in a row过滤一行有 n 个相等字符的字符串
【发布时间】:2015-08-06 22:07:36
【问题描述】:

是否有一个选项如何从字符串列表中过滤这些字符串,例如在一行中包含 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)]

但我不确定哪种方式更快 - 正则表达式还是这个。

【问题讨论】:

标签: python string list filter char


【解决方案1】:

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

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

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

【讨论】:

  • 感谢您的回答。很好的解决方案。我已经找到了一种方法 - 我已经编辑了我的帖子。
  • @Milan 您可以使用timeit 模块进行检查。但是 RegEx 版本可能比您的 any 版本更好。
  • 我的 猜测 是,如果字符串很长,正则表达式会更快,因为它只扫描每个字符串一次,而 any() 方法扫描 n 长度字符串 n 次。 OTOH,如果列表 do 中的大多数字符串都包含一组 3,并且该组往往出现在字符串的开头附近,那么 any() 方法 可能更快。
猜你喜欢
  • 2017-06-20
  • 1970-01-01
  • 1970-01-01
  • 2015-09-27
  • 2023-03-15
  • 2017-03-31
  • 2021-02-15
  • 2015-09-25
  • 2017-02-17
相关资源
最近更新 更多