深度阅读

How to use `yield` to create a generator in Python?

作者
作者
2023年08月22日
更新时间
13.32 分钟
阅读时间
0
阅读量

To use yield to create a generator in Python, you define a generator function that uses the yield keyword to generate a series of values one at a time. When a generator function is called, it returns a generator object, which is an iterator that can generate the values on demand. Here is an example of how to create a generator that yields Fibonacci numbers:

def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

fib = fibonacci()
for i in range(10):
    print(next(fib))

In this example, we define a generator function fibonacci() that uses a while loop to generate an infinite series of Fibonacci numbers. Each time the yield statement is encountered, the current value of a is returned as the next value in the series, and the function is paused until the next time next() is called on the generator object. To use the generator, we create a generator object fib by calling the fibonacci() function, and then we use a for loop to print the first 10 values in the series by calling next() on the generator object. The output of this code would be:

0
1
1
2
3
5
8
13
21
34

This is just one example of how to use yield to create a generator in Python. You can use the same principle to create generators that generate any sequence of values you need.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。