深度阅读

How to iterate over a generator object returned by a function using `yield`?

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

To iterate over a generator object returned by a function using yield, you can use a loop combined with the next() function to iterate through the sequence of values generated by the generator function. Here’s an example:

def my_gen():
    yield 1
    yield 2
    yield 3

g = my_gen()  # create a generator object

for value in g:
    print(value)  # output: 1, 2, 3

# Alternatively, you can use the next() function to iterate over the generator object    
g = my_gen()
print(next(g)) # output: 1
print(next(g)) # output: 2
print(next(g)) # output: 3

In this example, my_gen() is a generator function that yield values one at a time. g is a generator object returned by calling my_gen(). You can then use a for loop to iterate over g and print out each value generated by my_gen(). Alternatively, you can use the next() function to manually iterate through the values generated by g.

相关标签

博客作者

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