2012-01-05 91 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) ] 
相關問題