Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use list derivation in python

2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

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!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report