li = [i
for i in range(
100)
if i
%2==
0]
g = (i
for i in range(
100)
if i
%2==
0)
print(g.__next_
_())
print(g.__next_
_())
print(g.__next_
_())
print(
next(g))
from collections
import Iterable
print(isinstance(g, Iterable))
while True:
try:
print(g.__next__())
except StopIteration:
break
def gen():
while True:
try:
yield 'a'
except TypeError:
print(
'type error')
g = gen()
print(g.__next__())
g.throw(TypeError)
print(g.__next__())
1
a
type error
a
def fib(num):
a, b, count =
0,
1,
1
while count <= num:
yield b
a, b = b, a + b
count +=
1
g = fib(
10)
for i
in g:
print(i)
1 1 2 3 5 8 13 21 34 55
yield关键字
def fun():
a =
"world"
print(
"hello")
print(
1)
yield 2
print(
3)
yield 4
g = fun()
print(g)
for i
in g:
print(i)
<generator
object fun at
0x7fb57e85ceb8>
##generator
hello
1
2
3
4