test1 = [ x**2 for x in range(10)]
for i in test1:
print(i)
简介:
会在内存中生成一个抽象的对象,每次调用一次便会生成一次,和列表生成式不同的是没有预先将所有元素存储到内存当中,相比更加快更节省内存使用率
方法:
generator.__next__() #每执行一次调用下一个值
next(generator) #与上面方法一样
eg:
generator1 = (i**2 for i in range(10)) #定义一个生成器
for x in generator1:
print(x)
0
1
4
9
16
25
36
49
81
虽然和上面的列表生成式输出结果相同但是当数据量大时优势便会出现
自己定义函数函数内实现数据运算,再用yield返回最终的输出值
注意:yield所在位置即为函数停止位置,也就是说函数停止下面的语句将不会执行
eg:
import time
def func(max_number):
a,b,n = 0,1,0
while n < max_number:
yield b #规定为生成器的语句
a,b = b,a+b
n = n + 1
return None
f = func(10)
print(f.__next__())
print(f.__next__())
print(f.__next__())
print("==============stop==========")
time.sleep(3)
print(f.__next__())
print(f.__next__())
print(f.__next__())
print(f.__next__())
1
1
2
==============stop==========
3
5
8
13
import time
def consumer(name):
print("{%s} 准备吃饺子了"% name)
while True:
jiaozi = yield #将函数暂停到该位置
print("饺子{%s}来了,被{%s}吃了"%(jiaozi,name))
c = consumer("LiSi")
c.__next__()
c.__next__()
c.send("猪肉") #send语法,将值传递给yield
print("======================================")
print("\n")
########################################################
def producer(name):
c = consumer("AAA")
c2 = consumer("BBB")
c.__next__()
c2.__next__()
print("准备做饺子。。。")
for i in range(3):
time.sleep(1)
print("开始分饺子===")
time.sleep(1)
c.send(i)
c2.send(i)
producer("wangwu")
{LiSi} 准备吃饺子了
饺子{None}来了,被{LiSi}吃了
饺子{猪肉}来了,被{LiSi}吃了
======================================
{AAA} 准备吃饺子了
{BBB} 准备吃饺子了
准备做饺子。。。
开始分饺子===
饺子{0}来了,被{AAA}吃了
饺子{0}来了,被{BBB}吃了
开始分饺子===
饺子{1}来了,被{AAA}吃了
饺子{1}来了,被{BBB}吃了
开始分饺子===
饺子{2}来了,被{AAA}吃了
饺子{2}来了,被{BBB}吃了
针对可循环的数据类型(列表,元组,字典,字符串,以及生成器等等),
与生成器不同的是,生成器可以作用于for循环,还可以被next()函数不断调用并返回下一个值,直到最后抛出错误;
迭代器可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator
鉴别是否为可循环数据对象(Iterable)
from collections import Iterable
print("list---",isinstance([1,2,3,4],Iterable))
print("string---",isinstance('dasdsadas',Iterable))
/ list--- True
string--- True
鉴别是否为一个迭代器(Iterator)
有限字典,有限列表,有限字符串,元组都不是迭代器
from collections import Iterator
f = open('test.txt',"w+")
print("list---",isinstance([1,2,3,4],Iterator))
print("string---",isinstance('dasdsadas',Iterator))
print("file---",isinstance(f,Iterator))
f.close()
list--- False
string--- False
file--- True
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- efsc.cn 版权所有 赣ICP备2024042792号-1
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务