Content List Filtering

Given the list ['a','ab','abc','bac'] , I want to compute a list with strings that have 'ab' . That is, the result is ['ab','abc'] . How can this be done in Python?

+59
python list
Jan 28 '10 at 7:17
source share
6 answers

This simple filtering can be achieved in many ways using Python. The best approach is to use list comprehension as follows:

 >>> lst = ['a', 'ab', 'abc', 'bac'] >>> res = [k for k in lst if 'ab' in k] >>> res ['ab', 'abc'] >>> 

Another way is to use the filter function:

 >>> filter(lambda k: 'ab' in k, lst) ['ab', 'abc'] >>> 
+90
Jan 28 '10 at 7:20
source share
 [x for x in L if 'ab' in x] 
+14
Jan 28 '10 at 7:19
source share
 # To support matches from the beginning, not any matches: items = ['a', 'ab', 'abc', 'bac'] prefix = 'ab' filter(lambda x: x.startswith(prefix), items) 
+8
Jan 28 '10 at 7:22
source share

In the interactive shell, this was quickly tried:

 >>> l = ['a', 'ab', 'abc', 'bac'] >>> [x for x in l if 'ab' in x] ['ab', 'abc'] >>> 

Why does it work? Since in operator is defined for strings as follows: "is a substring".

In addition, you may need to write a loop rather than using the list comprehension syntax used above:

 l = ['a', 'ab', 'abc', 'bac'] result = [] for s in l: if 'ab' in s: result.append(s) 
+3
Jan 28 '10 at 7:19
source share
 mylist = ['a', 'ab', 'abc'] assert 'ab' in mylist 
0
Jan 28 '10 at 7:20
source share

what if you have a way out and you want to filter, starting with a specific phrase and ending with a specific phrase? For example, like the following phrase, and I need to find xx first and then filter 1234?

asdfasdfqwerhq xx 1234 xyz

-one
Dec 06 '18 at 20:12
source share



All Articles