Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use python generators

Shulou Source: shulou.com Published: 2022-06-01 04:58:34 09月25日 Update

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.

Tags: Generators articles generation functions time more iterations good practical not enough examples content parentheses articles ways square brackets methods concepts usage knowledge Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Apple Shulou Tech Info Shulou Technology MariaDB