人工智能,也就是python语言,是一种高级代码,在程序员的眼里,python就像胶水一样,他可以适应于各种情况,可以以最简单的代码去解决复杂的问题,现阶段python的使用率非常高,知乎就是以python代码编写的网站,而python也可以编写爬取sprider等非常方便的工具,今天达内小编为大家带来,python迭代器,希望大家喜欢!
生成器
·一个函数调用时返回一个迭代器,那么这个函数叫做生成器,如果函数中包含yield,那么这个函数就叫做生成器(自动生成或实现了可迭代协议),生成器的本质就是迭代器
1:生成器函数:内部使用了yield关键字 2:生成器表达式:列表推导式,返回的就是生成器
yield关键字
def func():
yield 1
yield 2
yield 3
yield 4
# 定义生成器
def my_rang(start, stop, step=0):
while start <= stop:
yield start + step
start += 1
# 获取生成器
number = my_rang(1, 7)
# 依次获取值
# print(number.__next__())
# print(number.__next__())
# print(number.__next__())
# print(number.__next__())
# print(number.__next__())
# print(number.__next__())
# print(number.__next__())
# 便利获取值
for i in my_rang(1, 7):
print(i)
print(“========================生成100个包子案例===========================”)
def product_baozi():
li = []
for i in range(100):
li.append(“包子%s” % i)
return li
l = product_baozi()
print(list(l))
def product_pro():
for i in range(100):
print(‘正在生产包子……’)
yield ‘以产包子%d' % i
print(’正在售卖包子‘)
p_pro = product_pro()
print(p_pro.__next__())
print(p_pro.__next__())
print(p_pro.__next__())
# 生成器效率高 内存占用小
# yield总结:
# 1、把函数做成迭代器
# 2、对比return,可以返回多次值,可以挂起/保存函数的运行状态
print(“=========================人口普查案例=======================”)
# def get_population():
# res =[]
# with open(“/files/population”, “r”, encoding=“utf-8”) as f:
# for i in f:
# res.append(i)
# return res
#
# p_gen = get_population()
# print(p_gen)
def get_population():
with open(“/files/population”, “r”, encoding=“utf-8”) as f:
for i in f:
yield i
# 获取生成器
p_gen = get_population()
# 统计总人口数
count = sum(eval(i)[“population”] for i in p_gen)
print(count)
ppp = get_population()
for i in ppp:
print(“%s 占统计人口的 %d %%” % (eval(i)['city'], count // eval(i)['population']))
print('=========================跑步案例=======================’)
def run():
i = 0
while True:
time.sleep(1)
print(‘from run’)
yield i
i += 1
f = run()
t = 0;
while t <= 1:
print(f.__next__())
t += 1
else:
print(“运行完成”)
# 几乎不占内存
su = sum(i for i in range(100))
print(su)
# 三元表达式
age = 10
t = True if age > 10 else False
# 列表推导式
lit = [i for i in range(100) if i % 2 == 0]
print(lit)
def test():
for i in range(4):
yield i
t = test()
t1 = (i for i in t)
t2 = (i for i in t1)
print(list(t1))
# t2为空,因为t2取自t1 ,在上面t1已经打印并且释放完了,所以t2为空
print(list(t2))
达内告诉我们,python的代码都很短,更多精彩内容尽在达内