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
原文地址:https://www.cnblogs.com/lianghong881018/p/11082395.html