* 使用圆括号()
创建一个生成器推导 *,它创建了一个可迭代的对象
使用next()函数可以获得生成器推导的下一个返回值
g = (i**2 for i in range(10))
** demo_1 **
斐波拉契数列(Fibonacci),除第一个和第二个数外,任意一个数都可由前两个数相加得到
** demo_2_generator **
处理多层嵌套列表
def flagtten(nested):
try:
for sublist in nested:
for element in flagtten(sublist):
yield element
except TypeError:#处理迭代单个对象引起的typeerror异常
yield nested
def main():
s = list(flagtten([1,[2,3]]))
print(s)
main()
def flagtten(nested):
try:
#不迭代类似于字符串的对象
try:
nested + ''
except TypeError:
pass
else:
raise TypeError
for sublist in nested:
for temp in flagtten(sublist):
yield temp
except TypeError:
yield nested
def main():
s = list(flagtten(["haha",["shan","san"]]))
print(s)
main()