**generators(生成器)**
generators(生成器)
生成迭代器:
function* get(){
let a = 1;
a++;
console.log(a);
yield 'abc';
let y = 2+a;
console.log(y);
yield 'hellow';
console.log('dapang');
yield '师徒教育';
yield '欢迎你';
yield '师徒课堂';
console.log(123);
yield '站在前方,为你导航';
}
let iter = get();
console.log(iter.next());
console.log(iter.next());
console.log(iter.next());
console.log(iter.next());
console.log(iter.next());
console.log(iter.next());
console.log(iter.next());
//依次打印:2
Object {value: "abc", done: false}
4
Object {value: "hellow", done: false}
dapang
Object {value: "师徒教育", done: false}
Object {value: "欢迎你", done: false}
Object {value: "师徒课堂", done: false}
123
Object {value: "站在前方,为你导航", done: false}
Object {value: undefined, done: true}
注释:1.生成器用来生成迭代器;
2.function函数名字中间有一个*号.
def fib(max):
a, b = 0, 1
while a < max:
yield a
a, b = b, a + b
>>> for i in fib(1000):
print(i)
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
>>>f = fib(1000)
>>>f.next() #python 3.0 要写成f.next() 否则出错
0
>>>f.next()
1
>>>f.next()
1
>>>f.next()
2