# The essence of generator is iterator
""" How to build a generator : 1 Generator function 2 Generator Expressions 3Python Some built-in functions provided , Return to a generator """
def func():
print('hello world')
yield 'good'
ret = func() # Generator object , Function does not execute
print(ret) # <generator object func at 0x0000027A22F72890>
# As long as... Appears in the function yield Then it is not an ordinary function , It's a generator function .
# Generators are essentially iterators , So pass next Method
print(next(ret)) # hello world good
# One yield Corresponding to one next
def func1():
yield 'what'
yield 'who'
res = func1()
print(next(res)) # what
print(next(res)) # who
""" return and yield return: End function , Return the value to the executor of the function yield: Do not end the function , Corresponding to next Return value """
# yield from: Return each element of an iteratable object to next; Save code , Improve efficiency ( Instead of for loop )
def func2():
l = [9, 8, 7]
yield from l
res2 = func2()
print(next(res2)) # 9
print(next(res2)) # 8
print(next(res2)) # 7
def func3(*args):
for i in args:
for j in i:
yield j
res3 = func3('hello', [1,2,3,6,7])
print(list(res3)) # ['h', 'e', 'l', 'l', 'o', 1, 2, 3, 6, 7]
def func4(*args):
for i in args:
# Instead of a for loop
yield from i
res4 = func4('hello', [1,2,3,6,7])
print(list(res4)) # ['h', 'e', 'l', 'l', 'o', 1, 2, 3, 6, 7]
# Generator Expressions
obj = (i for i in range(10))
print(obj) # <generator object <genexpr> at 0x000002ECD2AC9C10>
print(next(obj)) # 0
print(next(obj)) # 1
""" How to trigger a generator ( iterator ) Value : 1、next Method 2、for loop 3、 Convert it to a list """
# Interview questions
def add(n, i):
return n+i
def func5():
for i in range(4):
yield i
g = func5()
for n in [1, 10]:
g = (add(n, i) for i in g)
print(list(g))