Filtering a List of Strings Based on Their Contents
Given a list of strings, you may encounter the need to extract only those that contain a specific substring. In Python, there are several effective ways to perform this filtering operation.
Using List Comprehensions
One of the simplest and most recommended approaches is to utilize Python's powerful list comprehensions. List comprehensions provide a concise and expressive way to create a new list based on the elements of an existing one. For your specific requirement of filtering strings that contain 'ab', you can employ the following comprehension:
lst = ['a', 'ab', 'abc', 'bac']
result = [k for k in lst if 'ab' in k]
This comprehension iterates through each string in the original list ('a', 'ab', 'abc', 'bac') and checks if it contains the substring 'ab'. If true, it adds the string to the resulting list. This gives you the desired filtered list: ['ab', 'abc'].
Using the filter Function
Another method to filter strings in Python is to use the filter function. This function takes a filter function and an iterable as arguments and returns an iterator that yields the elements of the iterable that satisfy the filter function. In your case, you can use filter as follows:
lst = ['a', 'ab', 'abc', 'bac']
result = list(filter(lambda k: 'ab' in k, lst))
The filter function takes an anonymous function (lambda function) as its first argument, which checks if 'ab' exists in the input string. The second argument is the original list. The result of filter is an iterator, which is then casted to a list using list(). Again, this produces the desired ['ab', 'abc'] list.
While both list comprehensions and the filter function can achieve the desired filtering, list comprehensions are generally preferred for their conciseness and readability, especially for simple filtering tasks like this.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3