2012-01-05 70 views
0

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

我有一个列表

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'出名单的字符串。

如果你们可以告诉我一个关于如何在列表中寻找特定模式的广义方法,这将是一个很大的帮助。

+0

模式匹配可以用正则表达式来轻松实现。然后你可以迭代列表来进行匹配。 – 2012-01-05 11:57:56

回答

5

我会使用正则表达式:

>>> 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') 
1
import re 
pattern = re.compile('^([A-z]*)[,\.](\s*)([A-z]*)$') 
filtered = [ l for l in abc if re.match(pattern,l) ] 
相关问题