Home > Backend Development > Python Tutorial > How to filter list elements starting with a given prefix using Python?

How to filter list elements starting with a given prefix using Python?

WBOY
Release: 2023-08-20 11:29:40
forward
1786 people have browsed it

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”]
Copy after login

grammar

The following syntax is used in all examples -

startswith()
Copy after login

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()
Copy after login

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
Copy after login

This lambda function in Python is called an anonymous function. It can be used when a function object is required.

len()
Copy after login

This is a built-in method in Python that returns the length of the item in the object.

Use list comprehension

This program uses a list comprehension with a method called startswith() to filter the prefixed elements in the list.

The Chinese translation of

Example

is:

Example

In 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)
Copy after login

Output

 The given element start with prefix: ['Amar', 'Aman']
Copy after login

Use for loop

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 of

Example

is:

Example

In 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)
Copy after login

Output

 The given element start with prefix:
 ['banana', 'blue berry']
Copy after login

Use Filter() function

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

Example

is:

Example

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)
Copy after login
Output
 The given element start with prefix:
 ['bca', 'bcom']
Copy after login
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

is:

Example

In the following example, start using the function

filter_list_elements_prefix()

, which accepts two parameters -

lst

(to store the list) and

prefix

(in the function receive a specific prefix during the call). This function returns a new list by using a list comprehension, i.e. the expression item[:len(prefix)] slices the length of each item in lst from the beginning to the prefix and compares it with the prefix. If they are equal, include the item in the new list. Next, create a list to store some string values ​​in the variable

my_list

. 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)
Copy after login

输出

 The given element start with prefix:
 ['tea', 'teaspoon']
Copy after login

结论

我们讨论了解决问题陈述的各种方法,过滤以给定前缀开头的元素。有一些内置函数,如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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template