[Python学习笔记-005] 理解yield

网络上介绍yield的文章很多,但大多讲得过于复杂或者追求全面以至于反而不好理解。本文用一个极简的例子给出参考资料[1]中的讲解,因为个人觉得其讲解最为通俗易懂,读者只需要对Python的列表有所了解即可。

When you see a function with yield statements, apply this easy trick to 
understand what will happen:

1. Insert a line result = [] at the start of the function.
2. Replace each yield expr with result.append(expr).
3. Insert a line return result at the bottom of the function.
4. Yay - no more yield statements! Read and figure out code.
5. Compare function to original definition.

例如:

  • foo1.py
 1 #!/usr/bin/python3
 2 import sys
 3 
 4 def foo(n):
 5     for i in range(n):
 6         yield i * i
 7 
 8 def main(argc, argv):
 9     for i in foo(int(argv[1])):
10         print(i)
11     return 0
12 
13 if __name__ == '__main__':
14     sys.exit(main(len(sys.argv), sys.argv))
  • foo2.py
 1 #!/usr/bin/python3
 2 import sys
 3 
 4 def foo(n):
 5     result = []
 6     for i in range(n):
 7         result.append(i * i)
 8     return result
 9 
10 def main(argc, argv):
11     for i in foo(int(argv[1])):
12         print(i)
13     return 0
14 
15 if __name__ == '__main__':
16     sys.exit(main(len(sys.argv), sys.argv))
  •  meld foo1.py foo2.py

  •  运行foo1.py 和 foo2.py
lijin$ ./foo1.py 3
0
1
4
lijin$ ./foo2.py 3
0
1
4

那么,问题来了,

Q1 - yield的含义是什么?

A:相当于return, 不过返回的是一个生成器函数

Q2 - 为什么要引入yield?

A省内存如果使用return一个list, 则list的元素全部储存在内存里;如果使用yield, 那就只需要在访问某个元素时将对应的元素装入内存即可。更多内容,请参考《Python学习手册》第4版第20章。

参考资料:

  1. What does the "yield" keyword do?
原文地址:https://www.cnblogs.com/idorax/p/10209983.html