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 python generators

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

Share

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

This article will give you a detailed explanation on how to use python generators. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

Use python generators (generator)

The generator function allows you to create functions similar to iterators. They allow programmers to create iterators in a simple and fast way. Here is an example to illustrate this concept.

Suppose you want to sum the first 100000000 complete squares starting at 1.

It looks easy. You can easily do this with list derivation, but it takes too much input. Here is an example:

T1 = time.clock () sum ([I * i for i in range (1, 100000000)]) T2 = time.clock () time_diff = T2-T1 print (f "Ittook {time_diff} Secs to execute this method") # Ittook 13.1974940000006 Secs to execute this method

When increasing the complete square of the sum, this method is not flexible enough because it takes a lot of time to calculate. This is when the python generator comes in handy. After replacing square brackets with parentheses, the list deduction is changed to a generator expression. Now calculate the time spent:

T1 = time.clock () sum ((I * i for i in range (1, 100000000)) T2 = time.clock () time_diff = T2-T1 print (f "Ittook {time_diff} Secs to execute this method") # Ittook 9.53867000000001 Secs to execute this method on "how to use python generators" this article ends here, I hope the above content can be helpful to you, so that you can learn more knowledge, if you think the article is good Please 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