简体   繁体   中英

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.

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.

Just a guess, but...

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

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