How to use re match objects in a list comprehension

后端 未结 5 1910
说谎
说谎 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:43

    It could be shortened a little

    def filterPick(lines, regex):
        matches = map(re.compile(regex).match, lines)
        return [m.group(1) for m in matches if m]
    

    You could put it all in one line, but that would mean you would have to match every line twice which would be a bit less efficient.

提交回复
热议问题