1. Generators
Genenrators are any functions that have a yield statement.
2. yield statement
Inside a function, when the program meets the return statement,it will stop immediately. To return several vlues one at a time, there comes the yield statement. A yield statement circulaly return the values and wrap them in a generator object.
def flatten(nested):
for sublist in nested:
for element in sublist:
return element
nested=[[1,2],[3,4],[5,6]]
flatten(nested)
>>>
1 # the function will only return one value and terminate.
def flatten(nested):
for sublist in nested:
for element in sublist:
yield element
nested=[[1,2],[3,4],[5,6]]
flatten(nested)
>>>
<generator object flatten at 0x00000121F9D39518> # a generator object
list(flatten(nested)) #make it a list
>>>
[1, 2, 3, 4, 5, 6]
3. A recursive generator
def flattern(nested):
try:
for sublist in nested: # recursive case
for element in flattern(sublist):
yield element
except TypeError:# base case if nested is just a element, it will raise the
yield nested #TypeError: 'int' object is not iterable
4. Generator and iterator
The values of yield statement are wrapped in a generator object which is also an iterator.
本文深入探讨了Python中的生成器概念,包括其与yield语句的关系,递归生成器的应用,以及生成器与迭代器的区别。通过具体示例,展示了如何使用生成器简化复杂的数据处理流程。
1万+

被折叠的 条评论
为什么被折叠?



