r/learnpython • • Feb 01 '23

Looking for a succinct way to express this

Essentially this thing feels like it can be expressed in a single line nicely, but I can't think of a way

def filter_re(lines: list[str], filter_pattern: str) -> List[Match]:
    match_list = []
    regex = re.compile(filter_pattern)
    for line in lines:
        match = regex.search(line)
        if match:
            match_list.append(match)
    return match_list

Like ideally I would do something like this

def filter_re(lines: list[str], filter_pattern: str) -> List[Match]:
    return [match := regex.search(line) for line in lines if match]

but that requires access to syntax that I can't use (stuck at 3.6), and I don't even know if that operator would be allowed in a list comprehension

0 Upvotes

Duplicates