【问题标题】:Is there a way for checking a certain pattern in a list?有没有办法检查列表中的某个模式?
【发布时间】:2012-01-05 11:49:13
【问题描述】:

有没有办法检查某种模式,以便在使用该功能时可以打印列表中满足该模式的元素...例如

我有一个清单

abc=['adams, brian','smith, will',' and j.smith. there is a long string here','some more strings','some numbers','etc etc']

现在我想要的是从列表中取出所有格式为 'xyz,abc''x.abc' 的字符串。

如果你们能告诉我如何在列表中查找特定模式的通用方法,那将是一个很大的帮助。

【问题讨论】:

  • 模式匹配可以通过正则表达式轻松实现。然后,您可以遍历列表进行匹配。

标签: python list design-patterns


【解决方案1】:

我会使用正则表达式:

>>> import re
>>> exp = re.compile('(\w+\.\w+)|(\w+,\s?\w+)')
>>> map(exp.findall, abc)
[[('', 'adams, brian')], [('', 'smith, will')], [('j.smith', '')], [], [], []]

扁平化这个结果的函数方式:

>>> r = map(exp.findall, abc)
>>> filter(None, sum(sum(r, []), ()))
('adams, brian', 'smith, will', 'j.smith')

【讨论】:

    【解决方案2】:
    import re
    pattern = re.compile('^([A-z]*)[,\.](\s*)([A-z]*)$')
    filtered = [ l for l in abc if re.match(pattern,l) ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-10
      • 1970-01-01
      • 1970-01-01
      • 2015-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多