Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 201
P Moran Avatar asked Apr 30 '13 15:04

P Moran


People also ask

How do you match a string to a list in Python?

Python Find String in List using count() We can also use count() function to get the number of occurrences of a string in the list. If its output is 0, then it means that string is not present in the list. l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C'] s = 'A' count = l1.

How do you extract a string from a list in Python?

Calling str on each element e of the list l will turn the Unicode string into a raw string. Next, calling tuple on the result of the list comprehension will replace the square brackets with parentheses.

How do you check for partial match in Python?

Use the in operator for partial matches, i.e., whether one string contains the other string. x in y returns True if x is contained in y ( x is a substring of y ), and False if it is not. If each character of x is contained in y discretely, False is returned.


1 Answers

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.

like image 148
mgilson Avatar answered Oct 13 '22 01:10

mgilson