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 Generator and yield reasonably in python

2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces how to make rational use of the generator and yield in python, which can be used for reference by interested friends. I hope you can learn a lot after reading this article.

Rational use of generators (generator) and yield

% timeit-n 100a = (i for i in range (100000))% timeit-n 100b = [i for i in range (100000)] 100 loops, best of 3: 1.54 ms per loop100 loops, best of 3: 4.56 ms per loop

What you get with () is a generator object, and the memory required is independent of the size of the list, so it's more efficient. In specific applications, for example, set (i for i in range (100000)) is faster than set ([i for i in range (100000)]).

But for cases that require loop traversal:

% timeit-n 10 for x in (i for i in range (100000)): pass%timeit-n 10 for x in [i for i in range (100000)]: pass10 loops, best of 3: 6.51 ms per loop10 loops, best of 3: 5.54 ms per loop

The latter is more efficient, but if there is break in the loop, the benefits of using generator are obvious. Yield is also used to create generator.

Thank you for reading this article carefully. I hope the article "how to make rational use of python Generator and yield" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

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