How to use list derivation in python
This article is about how python uses list deductions. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
List derivation
If you don't know how to use list deduction yet, learn it quickly. As the author of this article said, "when I first learned this way, my whole world changed. "list derivation is really powerful, it is not only faster than the general method, but also very intuitive and readable. If you want to iterate through the list to do some operations, use it quickly.
Let's first define a simple function that calculates the square of the variable and adds 5:
> def stupid_func (x): > return Xerox 2 + 5
If we want to apply this function to odd items in the list, instead of using the list derivation, we will generally write it in the following form:
> my_list = [1,2,3,4,5] > > new_list = [] > for x in my_list: > > if x% 2! = 0: > new_list.append (stupid_func (x)) > print (new_list) [6,14,30]
But now that we have a list derivation, the above code can be changed to:
> my_list = [1,2,3,4,5] > > print ([stupid_func (x) for x in my_list if x% 2! = 0]) [6,14,30]
The general syntax of list derivation can be expressed as [expression for item in list]. If you want to add some Boolean conditional statements, then the above syntax can be changed to [expression for item in list if conditional], and its structure is actually equivalent to the following.
> for item in list: > > if conditional: > expression
The above list derivation can be further simplified, that is, there is no need to define a new function.
> print ([x * * 2 + 5 for x in my_list if x% 2! = 0]) [6,14,30] Thank you for reading! This is the end of this article on "how to use list-driven python". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!