Python笔记:1.6.2生成器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bq_cui/article/details/90064897
# -*- coding: utf-8 -*-
"""
Created on Fri May 10 14:09:18 2019

@author: Administrator
"""

def cube(n = 10):
    print('Generating cubes from 1 to %d' % (n**3))
    for i in range(1, n + 1):
        yield i**3
    
gen = cube()
print(gen)

for x in gen:
    print(x, end = ' ')
    
print('\n2--------------------\n')

gen = (x**3 for x in range(100))
print(gen)

print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))

print('\n3--------------------\n')
#print(gen)
#sum(gen, 1)

gen1 = (z**3 for z in range(3))
print(sum(gen1))
print(sum(gen1))

运行:

<generator object cube at 0x0000000009A801B0>
Generating cubes from 1 to 1000
1 8 27 64 125 216 343 512 729 1000 
2--------------------

<generator object <genexpr> at 0x0000000009AEE318>
0
1
8
27
64
125
216

3--------------------

9
0
 

猜你喜欢

转载自blog.csdn.net/bq_cui/article/details/90064897