python 生成器

nested = [[1,2],[3,4],[5]]
def flatten(nested):
for sublist in nested:
for element in sublist:
yield element
# 任何包含了yield语句的函数称为生成器,每次产一个值,函数就会被冻结一次,
for num in flatten(nested):
print(num)

print(list(flatten(nested)))

#example
g = ((i+2)**2 for i in range(2,27))
print(g.__next__())
print(g.__next__())

result:

1
2
3
4
5
[1, 2, 3, 4, 5]
16
25

 

posted @ 2019-06-25 13:48  嵌入式实操  阅读(89)  评论(0编辑  收藏  举报