简体   繁体   中英

Delete all items in a list that don't contain a regular expression string

Is it possible to delete all items in a list that don't contain a regular expression string?

I was thinking of maybe returning only a regular expression string, and if there wasn't one, making the list item empty, and then iterating over the list a second time to delete all the empty entries, but that seems inefficient.

Any thoughts?

For example, lets say I have:

["cat", "dog", "monkey", "Fred", "sad"]

and I write a regex that only selects for sad. I want all of the others to be (preferably) deleted.

The easiest way to do this is to construct a new list using a list comprehension:

regex = re.compile(...)
new_list = [s for s in old_list if regex.match(s)]

or, using filter() :

new_list = filter(regex.match, old_list)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM