python 生成器和迭代器
生成器
1.将li中的元素都乘以2
>>> li = [1,2,3,5,5,6,7,8,9,9,8,3] >>> li = [a*2 for a in li] >>> print(li) [2, 4, 6, 10, 10, 12, 14, 16, 18, 18, 16, 6]
生成器表达式形式:
一个一个取生成器的值 >>> li = [1,2,3,5,5,6,7,8,9,9,8,3] >>> li = (a*2 for a in li) >>> print(li) <generator object <genexpr> at 0x10565af10>#变成了一个生成器 >>> next(li) 2 >>> next(li) 4 >>> next(li) 6 >>> next(li) 10 for循环取生成器值,取完不会报错 一个一个取生成器的值 >>> li = [1,2,3,5,5,6,7,8,9,9,8,3] >>> li = (a*2 for a in li) >>> print(li) <generator object <genexpr> at 0x10565af10>#变成了一个生成器 >>> for i in li: ... print(i) ... 2 4 6 10 10 12 14 16 18 18 16 6 while循环取生成器,取完了会报错 >>> li = [1,2,3,5,5,6,7,8,9,9,8,3] >>> li = (a*2 for a in li) >>> while True: ... print(next(li)) ... 2 4 6 10 10 12 14 16 18 18 16 6 Traceback (most recent call last): File "<stdin>", line 2, in <module> StopIteration
生成器函数形式:
def func(n): count = 0 while count < n: print('count',count) count += 1 sign = yield count if sign == "stop": break new_func = func(4) #第一个执行方法时,是把函数变成了生成器 print(new_func) next(new_func)#第二次执行时,执行了一次函数,然后停在yield,并返回了count 输出结果: <generator object func at 0x1009fce60> count 0
def func(n): count = 0 while count < n: print('count',count) count += 1 sign = yield count if sign == "stop": break new_func = func(4) #第一个执行方法时,是把函数变成了生成器 print(new_func) next(new_func)#第二次执行时,执行了一次函数,然后停在yield,并返回了count #new_func.send("stop") #唤醒并执行yield,发送一个信息到生成器内部
迭代器
可迭代对象:可以直接for循环
1.集合数据类型:列表,字典,字符串等
2.生成器和带yield的generator方法
判断对象是否可迭代:isinstance
>>> from collections import Iterable >>> isinstance("abc",Iterable) True >>> isinstance([1,2,3],Iterable) True >>> isinstance(123,Iterable) False
迭代器:可以被next()函数调用并不断返回下一个值的对象。
iter(a) iter方法可以将变量变为迭代器
>>> from collections import Iterator >>> b = (a for a in range(10)) >>> isinstance(b,Iterator) True >>> a = "123" >>> isinstance(a,Iterator) False >>> a = iter(a) >>> isinstance(a,Iterator) True >>>