Santosh Narayanan
Santosh Narayanan

Reputation: 119

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

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.

Upvotes: 3

Views: 219

Answers (3)

Daniel Ruiz
Daniel Ruiz

Reputation: 620

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']

Upvotes: 1

Ajax1234
Ajax1234

Reputation: 71451

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)]

Upvotes: 2

Mahesh Karia
Mahesh Karia

Reputation: 2055

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)],.

Upvotes: 0

Related Questions