标签:判断 bre collect 直接 next 斐波那契 ret time iterator
[ i*2 for i in range(10) ]
生成器和列表的区别是生成器数据在调用时生成,不支持像列表一样可以切片等处理
只有一个"next"方法
>>> ( i*2 for i in range(10) )
>>> for i in b:
... print(i)
>>> c = ( i*2 for i in range(10) )
>>> c.__next__()
0
>>> c.__next__()
2
>>> c.__next__()
4
# Author:Li Dongfei
def fib(max):
n, a, b = 0, 0, 1
while n < max:
print(b)
a, b = b, a + b
n = n + 1
return "done"
fib(100)
# Author:Li Dongfei
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
return "done"
f = fib(100)
print(f.__next__())
print(f.__next__())
print(f.__next__())
print(f.__next__())
print(f.__next__())
# Author:Li Dongfei
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
return "done"
f = fib(10)
while True:
try:
x = next(f)
print('f:', x)
except StopIteration as e:
print('Generator return value:', e.value)
break
# Author:Li Dongfei
import time
def consumer(name): #消费者
while True:
baozi = yield
print("包子[%s]来了,被[%s]吃了!" % (baozi, name))
def producer(name): #生产者
c = consumer(name)
c.__next__()
for i in range(10):
time.sleep(1)
print("做了1个包子!")
c.send(i) #将i send到consumer会被yield接受到并且赋值给baozi
producer("dongfei")
可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator
>>> from collections import Iterable
>>> isinstance([],Iterable)
True
>>> isinstance((),Iterable)
True
>>> isinstance('abc',Iterable)
True
>>> from collections import Iterator
>>> isinstance( ( x for x in range(5) ), Iterator )
True
生成器一定是迭代器,但是迭代器不一定是生成器
>>> a = [1, 2, 3]
>>> b = iter(a)
>>> b.__next__()
1
>>> b.__next__()
2
>>> b.__next__()
3
标签:判断 bre collect 直接 next 斐波那契 ret time iterator
原文地址:https://www.cnblogs.com/L-dongf/p/9879712.html