How to use re match objects in a list comprehension

后端 未结 5 1900
说谎
说谎 2020-12-12 14:03

I have a function to pick out lumps from a list of strings and return them as another list:

def filterPick(lines,regex):
    result = []
    for l in lines:
         


        
5条回答
  •  执念已碎
    2020-12-12 14:17

    Starting Python 3.8, and the introduction of assignment expressions (PEP 572) (:= operator), it's possible to use a local variable within a list comprehension in order to avoid calling multiple times the same expression:

    # 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')]
    

    This:

    • Names the evaluation of re.compile('(a|r$)').search(x) as a variable match (which is either None or a Match object)
    • Uses this match named expression in place (either None or a Match) to filter out non matching elements
    • And re-uses match in the mapped value by extracting the first group (match.group(1)).

提交回复
热议问题