![](/img/trans.png)
[英]How to use regex re.compile Match() or findall() in list comprehension
[英]How to use re match objects in a list comprehension
我有一個函數從字符串列表中挑出塊並將它們作為另一個列表返回:
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')]
[m.group(1) for l in lines for m in [regex.search(l)] if m]
“技巧”是for m in [regex.search(l)]
部分中的for m in [regex.search(l)]
- 這就是你如何“分配”一個你需要多次使用的值,在列表理解中 - 添加這樣一個子句,其中對象“迭代”單個項目列表,其中包含您要“分配”給它的一個值。 有些人認為這在風格上是可疑的,但我覺得它有時候很實用。
return [m.group(1) for m in (re.search(regex, l) for l in lines) if m]
它可以縮短一點
def filterPick(lines, regex):
matches = map(re.compile(regex).match, lines)
return [m.group(1) for m in matches if m]
你可以將它全部放在一行中,但這意味着你必須匹配每一行兩次,效率會有點低。
啟動Python 3.8
,並引入賦值表達式(PEP 572) ( :=
運算符),可以在列表推導中使用局部變量,以避免多次調用相同的表達式:
# items = ["foo", "bar", "baz", "qurx", "bother"]
[(x, match.group(1)) for x in items if (match := re.compile('(a|r$)').search(x))]
# [('bar', 'a'), ('baz', 'a'), ('bother', 'r')]
這個:
re.compile('(a|r$)').search(x)
作為變量match
(其是None
或一個Match
對象) match
命名表達式( None
或Match
)來過濾掉不匹配的元素 match.group(1)
)重新使用映射值中的match
。 >>> "a" in "a visit to the dentist"
True
>>> "a" not in "a visit to the dentist"
False
這也適用於您在列表中搜索的搜索查詢
'P ='a','b','c'
P`中的'b'返回true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.