Python之生成器
程序员文章站
2022-05-31 23:26:52
...
generator:生成器
generator中保存的是算法,在调用时才计算。
1、列表生成式转 generator
L = [x*x for x in range(10)] ###列表
g = (x*x for x in range(10)) ###generator
通过next(g)一个一个打印元素:>>>next(g)
0
>>>next(g)
1
>>>next(g)
4
通过for循环打印(因为generator是可迭代对象):
for n in g:
print(n)
通过list打印:print(list(g))
2、函数实现generator:
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
return 'done'
print(list(fib(6)))
来看一个网上的面试题:
def add(n,i):
return n+i
def test():
for i in range(4):
yield i
g = test()
for n in [1,10,5]:
g = (add(n,i) for i in g)
print(list(g))的结果是多少?
正确答案是[15,16,17,18]
个人理解过程如下:
当n为1时,此时g为初始generator test,执行for循环代码重新给g赋值:
g = (add(n,i) for i in test())
当n为10时,此时g为上面的generator,执行for循环代码重新给g赋值:
g = (add(n,i) for i in (add(n,i) for i in test()))
当n为5时,g为上面新的generator,执行for循环重新给g赋值:
g = (add(n,i) for i in (add(n,i) for i in (add(n,i) for i in test())))
当执行print(list(g))时,是要打印g中所有数据,此时g进行实际的计算:当前n为5,test返回的是[0,1,2,3],带入g的公式中
g = (add(5,i) for i in (add(5,i) for i in (add(5,i) for i in (0,1,2,3))))
g = (add(5,i) for i in (add(5,i) for i in (5,6,7,8))
g = (add(5,i) for i in (10,11,12,13))
最后g中数据为(15,16,17,18)
以上为个人理解,如有意见和建议欢迎反馈
generator中保存的是算法,在调用时才计算。
1、列表生成式转 generator
L = [x*x for x in range(10)] ###列表
g = (x*x for x in range(10)) ###generator
通过next(g)一个一个打印元素:>>>next(g)
0
>>>next(g)
1
>>>next(g)
4
通过for循环打印(因为generator是可迭代对象):
for n in g:
print(n)
通过list打印:print(list(g))
2、函数实现generator:
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
return 'done'
print(list(fib(6)))
来看一个网上的面试题:
def add(n,i):
return n+i
def test():
for i in range(4):
yield i
g = test()
for n in [1,10,5]:
g = (add(n,i) for i in g)
print(list(g))的结果是多少?
正确答案是[15,16,17,18]
个人理解过程如下:
当n为1时,此时g为初始generator test,执行for循环代码重新给g赋值:
g = (add(n,i) for i in test())
当n为10时,此时g为上面的generator,执行for循环代码重新给g赋值:
g = (add(n,i) for i in (add(n,i) for i in test()))
当n为5时,g为上面新的generator,执行for循环重新给g赋值:
g = (add(n,i) for i in (add(n,i) for i in (add(n,i) for i in test())))
当执行print(list(g))时,是要打印g中所有数据,此时g进行实际的计算:当前n为5,test返回的是[0,1,2,3],带入g的公式中
g = (add(5,i) for i in (add(5,i) for i in (add(5,i) for i in (0,1,2,3))))
g = (add(5,i) for i in (add(5,i) for i in (5,6,7,8))
g = (add(5,i) for i in (10,11,12,13))
最后g中数据为(15,16,17,18)
以上为个人理解,如有意见和建议欢迎反馈
上一篇: pandas之read_csv
下一篇: Python之生成器