Reputation: 793
In a list of string, how to remove string which are part of other string in the list?
Here is an example.
lst = ['Hello World', 'Hello', 'This is test', 'is test']
I would like to only get ['Hello World', 'This is test']
as the output.
Upvotes: 0
Views: 69
Reputation: 48357
You can apply list comprehension
in order to filter list.
Also, use filter
method by applying a lambda
expression as argument.
lst = ['Hello World', 'Hello', 'This is test', 'is test']
lst = [string for string in lst if len(list(filter(lambda x: string in x, lst))) == 1]
Output
['Hello World', 'This is test']
Upvotes: 1
Reputation: 71451
You can use any
:
lst = ['Hello World', 'Hello', 'This is test', 'is test']
new_results = [a for i, a in enumerate(lst) if any(h in a and c != i for c, h in enumerate(lst))]
Output:
['Hello World', 'This is test']
Upvotes: 1