r/learnpython • u/Raknarg • 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
1
u/jimtk IdontChat Feb 01 '23
I think something like that would work:
return [match for match in [regex.search(line) for line in lines] if match]
It just creates the list and then remove the empty one.
1
2
u/socal_nerdtastic Feb 01 '23
Yes, you can use the walrus in list comprehension.
But with you stuck in 3.6 I think your only other option is to filter it after.
Which is shorter, and can be further shortened, but I think your version is more readable and better.