python generator(生成器)

时间:2023-03-09 04:20:57
python generator(生成器)
a=(x*2 for x in range(1000))
# print(a.next())#python2使用
print(a.__next__()) #python3使用
print(next(a)) #python2和python3均可使用

send的用法:

def func():
print('one')
result = yield 'two'
print(result)
print('four')
rr = yield 'five'
print(rr, 'six') a = func()
print(a.send(None))
# a.__next__()
print(a.send('three'))

输出:

one
two
three
four
five