Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use re match objects in a list comprehension

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:         match = re.search(regex,l)         if match:             result += [match.group(1)]     return result 

Is there a way to reformulate this as a list comprehension? Obviously it's fairly clear as is; just curious.


Thanks to those who contributed, special mention for @Alex. Here's a condensed version of what I ended up with; the regex match method is passed to filterPick as a "pre-hoisted" parameter:

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')] 
like image 521
Brent.Longborough Avatar asked Mar 12 '10 23:03

Brent.Longborough


People also ask

How do you're match an object in Python?

If you want to match a full string against a pattern then use re. fullmatch() . The re. fullmatch method returns a match object if and only if the entire target string from the first to the last character matches the regular expression pattern.

How does re match work in Python?

Both return the first match of a substring found in the string, but re. match() searches only from the beginning of the string and return match object if found. But if a match of substring is found somewhere in the middle of the string, it returns none.

What is the purpose of re match function in re module?

match() function of re in Python will search the regular expression pattern and return the first occurrence. The Python RegEx Match method checks for a match only at the beginning of the string. So, if a match is found in the first line, it returns the match object.

Can you use continue in list comprehension?

The concept of a break or a continue doesn't really make sense in the context of a map or a filter , so you cannot include them in a comprehension.


1 Answers

[m.group(1) for l in lines for m in [regex.search(l)] if m] 

The "trick" is the for m in [regex.search(l)] part -- that's how you "assign" a value that you need to use more than once, within a list comprehension -- add just such a clause, where the object "iterates" over a single-item list containing the one value you want to "assign" to it. Some consider this stylistically dubious, but I find it practical sometimes.

like image 185
Alex Martelli Avatar answered Sep 20 '22 23:09

Alex Martelli