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 Yield syntax in Python

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

Share

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

This article mainly introduces how to use Yield grammar in Python, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, let the editor take you to understand it.

Yield syntax in Python

For example, here we define a fibonacci () function that enumerates the first n digits of the Fibonacci sequence: 0, 1, 1, 2, 3, 5.

Def fibonacci (n): a = 0b = 1 nums = [] for _ in range (n): nums.appends (a) a, bb = b, axib return nums for i in fibonacci (10): print (I)

We can modify the fibonacci () function to use the yield syntax in Python:

First, rewrite append into yield.

Then delete the num list

In this way, the program will be the same as above, yield a says, every time we calculate an element, we send it out immediately; we don't need to wait for the whole list to be generated before outputting it; the advantage of yield is that it outputs in time in some very time-consuming operations.

Def fibonacci (n): a = 0b = 1 for _ in range (n): yield an a, bb = b, aquib return nums for i in fibonacci (10): print (I) Thank you for reading this article carefully. I hope the article "how to use Yield Grammar in Python" shared by the editor will be helpful to you. At the same time, I hope you will support me 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