我有一個函數從字符串列表挑選出腫塊,並返回它們作爲另一個列表使用重新匹配對象:如何在列表理解
def filterPick(lines,regex):
result = []
for l in lines:
match = re.search(regex,l)
if match:
result += [match.group(1)]
return result
有沒有辦法重新制定這個作爲一個列表理解?顯然這是相當清楚的;只是好奇。
感謝那些貢獻者,特別提到@Alex。這裏是我最終結果的簡明版本;正則表達式匹配方法傳遞到filterPick作爲「前懸掛」參數:
import re
def filterPick(list,filter):
return [ (l, m.group(1)) for l in list for m in (filter(l),) if m]
theList = ["foo", "bar", "baz", "qurx", "bother"]
searchRegex = re.compile('(a|r$)').search
x = filterPick(theList,searchRegex)
>> [('bar', 'a'), ('baz', 'a'), ('bother', 'r')]
亞歷克斯,我喜歡那樣;感謝和+1。我有一些相當繁重的工作來處理這段代碼 - 我是否應該擔心設置和拆除「虛擬迭代器」的額外開銷?順便說一句,我贊成「稍後優化」的原則。 – 2010-03-13 00:12:57
@Brent,對於搜索調用,「虛迭代器」應該可以忽略不計;一個較小的優化是使用'(regex.search(l),'''代替'[regex.search(l)]'(我發現它更易讀,但速度更慢 - 我認爲你不可能是因爲你實際上正在調用模塊的're.search'函數,而不是re對象的方法。將'regex.search'作爲listcomp之外的綁定方法拉動是另一個次要但有用的優化,順便提一下, – 2010-03-13 01:15:07
as當我看到你的答案時,我意識到使用re.search並不是最好的方法,你能否澄清一下你如何「將regex.search作爲listcomp之外的綁定方法」?我真的很感激你對listcomp和Python noob的耐心等待 – 2010-03-13 10:08:31