Slicing a Python list based on ending with one of a set of substrings

Viewed 134

I have a python list

list1 = ['TC_TEST1', 'TC_TEST1_TEST2', 'TC_TEST3', 'TC_TEST1TEST2']

sublist1 = ['TEST1', 'TEST3']

Desired output is

result = ['TC_TEST1', 'TC_TEST3']

It should not contain patterns in sublist1 that occur in middle or other places in the string.

I tried using

result = [s for s in list1 if any(xs in s for xs in sublist1)]

but this also prints the patterns wherever it occurs in the string, not only the ending part.

3 Answers

You can try this:

list1 = {'TC_TEST1', 'TC_TEST1_TEST2', 'TC_TEST3', 'TC_TEST1TEST2'}
sublist1 = { 'TEST1', 'TEST3'}
final_list = [i for i in list1 if any(i.endswith(b) for b in sublist1)]

Output:

set(['TC_TEST3', 'TC_TEST1'])

Advanced feature with tuples:

sublist1 = ('TEST1', 'TEST3')
final_list = [i for i in list1 if i.endswith(sublist1)]

First, you need to notice that you haven't defined python lists, but sets. These are the equivalent lists derived from your defined sets (notice the []notation):

list1 = ['TC_TEST1TEST2', 'TC_TEST3', 'TC_TEST1', 'TC_TEST1_TEST2']
sublist1 = ['TEST1', 'TEST3']

If you need to filter the strings that only ends with a list of possible substrings, you can call the endswith method of a Python string passing a tuple of strings as an argument. That way, your desired output can be derived using the following expression:

result = [s for s in list1 if s.endswith(tuple(sublist1))]

Actual output is:

>>> result
['TC_TEST3', 'TC_TEST1']

Instead of using in use endswith() function so just replace result = [s for s in list1 if any(xs in s for xs in sublist1)] with result = [s for s in list1 if any(s.endswith(xs) for xs in sublist1)],.

Related