blog

Welcome to my blog!

Python:yeild

ab's Avatar 2024-03-16 Accumulate

  1. 1. yeild与return
  2. 2. 举例说明

yeild与return

在编程的世界里,理解各种概念往往是进步的阶梯。今天,我们来探讨一个在 Python 中相当有趣且强大的关键字:yield。如果你对它还感到陌生,不妨将 yield 视作 return 的同胞兄弟。是的,它们都承担着在函数中返回某种结果的重要职责。但事实上,yieldreturn 在功能上有着本质的不同。

  • 使用 return 的函数:这类函数在执行到 return 语句时,会直接返回所有结果。一旦返回结果,程序便终止运行,并且局部变量被销毁。这种方式简单直接,但在处理大量数据时可能会导致内存问题。

  • 搭载 yield 的函数:相较于 returnyield 提供了一种优雅的机制,允许函数返回一个可迭代的生成器(generator)对象。这意味着函数的执行可以在 yield 处被暂停,并在需要的时候继续从上次离开的地方执行。你可以通过 for 循环或 next() 方法遍历这个生成器对象,逐一提取结果,这种方式大大节约了内存使用。

那么,生成器到底是什么呢?简单来说,在 Python 中,任何使用了 yield 的函数 都会被视为一个生成器。这听起来可能有点像是语言的套娃游戏,但这正是其魅力所在。通过调用含有 yield 的函数,你实际上得到的是一个生成器对象。这个对象背后隐藏着强大的潜力,能够以极低的内存消耗处理大量数据。

为什么使用生成器? 使用生成器的一个主要原因是其高效的内存利用特性。想象一下处理一个庞大的数据集合,如果一次性加载进内存,无疑会给系统带来巨大的压力。而生成器则允许我们逐步处理数据,只在需要时才生成下一个元素,这种“按需获取”的策略显著降低了内存的使用。


举例说明

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
def return_example():
print("This is the first line.")
return "Return statement"
print("This line will not be executed.")

def yield_example():
print("This is the first line.")
yield "Yield statement"
print("This line will be executed after the first yield.")
yield "Second yield statement"
print("This line will be executed after the second yield.")

# 使用return关键字
result_return = return_example()
print(result_return)

# 使用yield关键字
result_yield = yield_example()
print(next(result_yield))
print(next(result_yield))

输出结果:

1
2
3
4
5
6
7
8
(d2l) (base) chenyubin@chenyubindeMacBook-Pro d2l % /Users/chenyubin/anaconda3/envs/d2l/bin/python /Users/chenyubin/Desktop/no_emo/gi
thub/d2l/test.py
This is the first line.
Return statement
This is the first line.
Yield statement
This line will be executed after the first yield.
Second yield statement
本文最后更新于 天前,文中所描述的信息可能已发生改变
Perfect Night
LE SSERAFIM