list1 = [x*3 for x in range(10)] print(type(list1)) g = (x*3 for x in range(10)) print(type(g)) print(next(g))
用生成器的好处在于不用一次开辟所有空间,每次去数子再运算即可
def fib(length): a, b = 0, 1 n = 0 while n < length: a, b = b, a + b n += 1 yield b #可以近似理解为return b g = fib(100) print(g) #得到的是一个生成器 print(next(g)) print(next(g)) print(next(g)) print(next(g)) print(next(g)) print(next(g)) print(next(g)) print(next(g))
生成器用于多线程:
def thread1(): for i in range(10): yield None print("--{}--".format(i)) def thread2(): for i in range(10): yield None print("++{}++".format(i)) g1 = thread1() g2 = thread2() while True: try: for i in range(10): #用生成器来实现交替进行函数 next(g1) next(g2) except: break