Home >Backend Development >Python Tutorial >How to filter list elements starting with a given prefix using Python?
The word prefix is defined by the beginning of a word or letter. In this article, we will learn how to filter list elements starting with a given prefix using Python using Python built-in functions like startswith(), filter(), lambda, and len().
Let us take an example to understand this problem−
Let’s take an example to understand this: Given element list, My_list = [“Amelia”, “Kinshuk”, “Rosy”, “Aman”] Keyword to be searched, Prefix = “Am” Final result = [“Amelia”, “Aman”]
The following syntax is used in all examples -
startswith()
This is a built-in method in Python that returns true if the given condition is met and the string starts with a specific value.
filter()
The filter() method is applied when we need to filter items based on specific conditions. Simply put, it allows the user to iterate over those elements that satisfy a condition.
lambda
This lambda function in Python is called an anonymous function. It can be used when a function object is required.
len()
This is a built-in method in Python that returns the length of the item in the object.
This program uses a list comprehension with a method called startswith() to filter the prefixed elements in the list.
The Chinese translation ofIn the following example, we will use a list comprehension in the return statement of a function named prefix_list_element_filter() which will iterate over the list values using a for loop and startswith ()Check prefix. The combination of a for loop and an if statement in the same position is called a list comprehension. Then create the list in the variable my_list. Continuing with the setup of the calling function, pass the parameters my_list (stored list value) and Am (prefix) to filter list elements that start with the given prefix. Finally, we use the variable filter_list to print the results.
def prefix_list_element_filter(lst, prefix): return [item for item in lst if item.startswith(prefix)] # Create the list my_list = ["Amar", "Bunny", "Aman", "Ganesh", "Rajendra"] filter_list = prefix_list_element_filter(my_list, "Am") print("The given element start with prefix:", filter_list)
The given element start with prefix: ['Amar', 'Aman']
The program uses a for loop to iterate over the given list and checks the prefix using startswith(). It will then use an empty list to store the filtered prefix elements by using a built-in method called append().
The Chinese translation ofIn the following example, we first start the program by defining a function using the def keyword, which accepts two parameters - lst (for receiving list values) and prefix (for receiving prefix keywords). Next, it will iterate over the list using a for loop and then set the prefix using the startswith() method, which accepts the parameter prefix value received by the function. The filtered list elements are then added to the variable filtered_list using a method called append() and the result is returned. Now create the list in variable fruit_list. Then use the call function to pass the list value and prefix parameters into the variable filter_list. Finally, the results are printed using a variable named filter_list.
def prefix_list_element_filter(lst, prefix): filtered_list = [] for item in lst: if item.startswith(prefix): filtered_list.append(item) return filtered_list # Create the list fruit_list = ["apple", "banana", "avocado", "blue berry", "kiwi"] filter_list = prefix_list_element_filter(fruit_list, "b") print("The given element start with prefix:\n", filter_list)
The given element start with prefix: ['banana', 'blue berry']
The program uses the filter() function to identify specific prefixes and uses the lambda function to set the prefix through a method called startswith(), which can be used to filter specific prefixes.
The Chinese translation of In the following example, a function starting with the def keyword is used, which accepts two parameters - lst (receives a list value) and prefix (receives a specific keyword search), this function will filter the list of items based on whether they start with a given prefix. This function returns a prefixed result. Then create a list to store the string values in variable course_list. Next, use a function call to pass the values - pass course_list and "bc" in the variables filter_list. Now use the print function setting the variable name filter_list to get the results.
def prefix_list_element_filter(lst, prefix):
return list(filter(lambda item: item.startswith(prefix), lst))
# Create the list
course_list = ["dca", "bca", "bcom", "MCA", "pgdca"]
filter_list = prefix_list_element_filter(course_list, "bc")
print("The given element start with prefix:\n", filter_list)
Output
The given element start with prefix:
['bca', 'bcom']
Using list comprehensions with conditional expressions
This program uses a function that returns list compression by setting some conditional expressions that can be used to filter list elements that start with a given prefix.
The Chinese translation of Example
, which accepts two parameters -
lst. Then initialize the variable filter_list, which has the same name as the above function, to pass the values of the list and prefix. Finally, use the variable filter_list to get the results in the print function.
def filter_list_elements_prefix(lst, prefix):
return [item for item in lst if item[:len(prefix)] == prefix]
# Create the list
my_list = ["tea", "coffee", "cheese", "teaspoon", "sugar"]
filter_list = filter_list_elements_prefix(my_list, "tea")
print("The given element start with prefix:\n", filter_list)
输出
The given element start with prefix:
['tea', 'teaspoon']
结论
我们讨论了解决问题陈述的各种方法,过滤以给定前缀开头的元素。有一些内置函数,如startswith(),append()和len(),可以用于过滤前缀并根据给定条件返回结果。这个程序涉及到现实生活中的例子,比如一个由多个人名组成的名单,可以通过特定的前缀进行搜索。
The above is the detailed content of How to filter list elements starting with a given prefix using Python?. For more information, please follow other related articles on the PHP Chinese website!