什么是生成器呢?
生成器与函数的定义方法类似,只是需要yield关键字处理每一个需要迭代的值(普通函数需要return返回值)。
def myGenerater():
numlist = [1, 2, 3, 4, 5, 6, 7, 8]
for num in numlist:
yield num
for num in myGenerater():
print(num, end=' ')
如何把一个二维列表转换为一维列表呢?
nestedlist = [[1, 2, 3], [4, 3, 2], [1, 2, 3, 5, 6, 9]]
def enumlist(nestedlist):
for sublist in nestedlist:
for element in sublist:
yield element
for num in enumlist(nestedlist):
print(num, end=' ')
问题又来了,如何将任意多维的列表转化成一维呢
这就需要用到递归
nestedlist = [4, [1, 2, [3, 6]], [4, [3, 2, 5, [9, 4]]], [1, 2, 3, 5, 6, 9]]
def enumlist(nestedlist):
try:
for sublist in nestedlist:
for element in enumlist(sublist): #递归
yield element
except TypeError:
yield nestedlist #如果是单个的值就迭代
for num in enumlist(nestedlist):
print(num, end=' ')