P Moran
P Moran

Reputation: 1842

In python, how do i extract a sublist from a list of strings by matching a string pattern in the original list

How do i return a sublist of a list of strings by using a match pattern. For example I have

myDict=['a', 'b', 'c', 'on_c_clicked', 'on_s_clicked', 's', 't', 'u', 'x', 'y']

and I want to return:

myOnDict=['on_c_clicked', 'on_s_clicked']

I think list comprehensions will work but I'm puzzled about the exact syntax for this.

Upvotes: 7

Views: 18392

Answers (2)

Kyle G.
Kyle G.

Reputation: 880

Just a guess, but...

for entry in myDict:
    if re.search("^on", entry):
        myOnDict.append(entry)

Upvotes: 0

mgilson
mgilson

Reputation: 310069

import re
myOnDict = [x for x in myDict if re.match(r'on_\w_clicked',x)]

should do it...


Of course, for this simple example, you don't even need regex:

myOnDict = [x for x in myDict if x.startswith('on')]

or:

myOnDict = [x for x in myDict if x.endswith('clicked')]

or even:

myOnDict = [x for x in myDict if len(x) > 1]

Finally, as a bit of unsolicited advice, you'll probably want to reconsider your variable names. PEP8 naming conventions aside, these are list objects, not dict objects.

Upvotes: 16

Related Questions