How to use re match objects in a list comprehension

2024/11/19 17:40:21

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 redef 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')]
Answer
[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.

https://en.xdnf.cn/q/26417.html

Related Q&A

How do I run pip on python for windows? [duplicate]

This question already has answers here:Why does "pip install" inside Python raise a SyntaxError?(6 answers)Closed 8 years ago.Ive just installed python 3.5, ran Python 3.5 (32-bit) and typed…

Select certain rows by index of another DataFrame

I have a DataFrame and I would select only rows that contain index value into df1.index. for Example: In [96]: df Out[96]:A B C D 1 1 4 9 1 2 4 5 0 2 3 5 5 1 0 22 1 3 9 6and these ind…

Execute .sql schema in psycopg2 in Python

I have a PostgreSQL schema stored in .sql file. It looks something like:CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY,facebook_id TEXT NOT NULL,name TEXT NOT NULL,access_token TEXT,created I…

AttributeError: module html.parser has no attribute HTMLParseError

This is the hints,how can I resolve it? I use Python 3.5.1 created a virtual envirement by virtualenv The source code works well on my friends computer machineError: Traceback (most recent call last):…

Error message python-pylint C0103:Invalid constant name

Im confused about the error(s) in this photo:I dont know how to fix them. My program is a Python-Flask web frame. When I use Visual Studio Code to debug my program, Pylint shows these errors. I know th…

How to use virtualenv with python3.6 on ubuntu 16.04?

Im using Ubuntu 16.04, which comes with Python 2.7 and Python 3.5. Ive installed Python 3.6 on it and symlink python3 to python3.6 through alias python3=python3.6.Then, Ive installed virtualenv using s…

Is a day always 86,400 epoch seconds long?

While reviewing my past answers, I noticed Id proposed code such as this:import timedef dates_between(start, end):# muck around between the 9k+ time representation systems in Python# now start and end …

Find the first instance of a nonzero number in a list in Python [duplicate]

This question already has answers here:Return the index of the first element of a list which makes a passed function true(7 answers)Closed last year.I have a list like this: myList = [0.0, 0.0, 0.0, 2.…

How to debug a Python module in Visual Studio Codes launch.json

My question may seem simple but, I have a module that I launch in a terminal like this: python -m my_module.my_fileHow do I debug this in Visual Studio Code? I have this in my launch.json (documentati…

Cleanest Fastest server setup for Django [closed]

Closed. This question is opinion-based. It is not currently accepting answers.Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.Clo…