KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
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')]
Tags (comma-separated)
Save Edits
Cancel