About Generator

Generators are relatively new to Python, and are (along with iterators) perhaps one of the most powerful features to come along for years.
The following example is a function that flattens nested lists.
def flatten(nested):
       for sublist in nested:
             for element in sublist:
                   yield element

nested = [[1, 2], [3, 4], [5]]
>>> flatten(nested)
<generator object flatten at 0x924d93c>
>>> list(flatten(nested))
[1, 2, 3, 4, 5]
So what's new here is the yield statement. Any function that contains a yield statement is called a generator.  The difference between normal function and generator is that instead of returning one value, as you do with return, you can yield several values, one at a time. Each time a value is yielded (with yield), the function freezes;  that is, it stops its execution at exactly that point and waits to be reawakened. When it is, it resumes its execution at the point where it stopped. Finally the generator function will return a generator object which contain all the yielded values and you can use some function to process the object, like list().
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值