Iterater and generator in Python
Try to answer the following question?
How do generators save memory?
When is the best time to use a generator?
How can I use itertools to create complex generator workflows?
When is lazy evaluation beneficial, and when is it not?
Programmer who is familiar with another language start learning Python, they are taken aback by the difference in for loop notation.
With the influence from others language, they may try to finish iteration job by this code:
|
|
What the beginner don’t know the implemenation of function range in Python(2.7). The first thing the range() function must precreate the list of all numbers within the range.
In Python2.7, range() produce a list but xrange() return a iterator.( In Python 3, the range() is replaced with the xrange() and there is no xrange() function anymore. From this modification, programmer can know that the develop team of Python aware that it’s neccessary to force the user to use a generator when they want to iteration job.)
Here is a test for the differences between the range() and xrange() in memory allocation.
作者: Jason Leaster
来源: http://jasonleaster.github.io
链接: http://jasonleaster.github.io/2016/04/09/iterater-and-generator-in-python/
本文采用知识共享署名-非商业性使用 4.0 国际许可协议进行许可