当前位置: 首页 > news >正文

中国最著名网站建设公司企业宣传网站

中国最著名网站建设公司,企业宣传网站,做网站实习日志,网站怎么做直播迭代器 Python 迭代器是一种对象,它实现了迭代协议,包括 __iter__() 和 __next__() 方法。迭代器可以让你在数据集中逐个访问元素,而无需关心数据结构的底层实现。与列表或其他集合相比,迭代器可以节省内存,因…

迭代器       

Python 迭代器是一种对象,它实现了迭代协议,包括 __iter__() 和 __next__() 方法。迭代器可以让你在数据集中逐个访问元素,而无需关心数据结构的底层实现。与列表或其他集合相比,迭代器可以节省内存,因为它们一次只生成一个元素。

迭代器的基本特点

  1. 懒加载:迭代器不会一次性将所有数据加载到内存中,而是根据需要生成元素。
  2. 状态保持:迭代器在迭代过程中会保持其状态,可以从上次停止的地方继续迭代。
  3. 可以遍历:迭代器是可遍历的,可以使用 for 循环等结构来进行遍历。

 下面的代码可以看出迭代器在节省内存方面的作用。

import sys
import random# 生成 1-100的随机数的集合,共1000个元素
numbers = [random.randint(1, 100) for _ in range(1000)]
iterator = iter(numbers)# 打印对象的内存大小
print(sys.getsizeof(numbers))   # 9016
print(sys.getsizeof(iterator))  # 48

 迭代器的经典demo:

# 创建一个简单的迭代器
class MyIterator:def __init__(self, limit):self.limit = limitself.current = 0def __iter__(self):return selfdef __next__(self):if self.current < self.limit:self.current += 1return self.currentelse:raise StopIteration# 使用迭代器
for num in MyIterator(5):print(num)

 迭代器在读取大文件的经典应用:

with open('users.csv', 'r') as file:for line in file:print(line.strip())

         逐行读取文件内容,而不需要将整个文件加载到内存中。这种方法节省了内存资源,特别是在处理非常大的文件时。

生成器

生成器是一种特殊类型的迭代器,它允许你在函数中暂停执行并在以后继续。 

使用 yield 的基本概念

  1. 生成器函数:当一个函数包含yield语句时,它不再是一个普通的函数,而是一个生成器函数。当调用这个函数时,它不会立即执行,而是返回一个生成器对象。

  2. 状态保留:每次调用生成器的__next__()方法(或者使用next()函数)时,生成器函数会从上次执行的位置继续执行,直到遇到下一个yield语句。在此时,函数的执行状态(包括局部变量)会被保留。

  3. 迭代:生成器可以被用于迭代,像普通的列表或其他可迭代对象一样。使用for循环可以逐个获取生成器产生的值。

# 定义一个生成器函数
def read_users():with open('users.csv', 'r') as file:for line in file:yield line.strip()r1 = read_users()  # 定义一个生成器对象
r2 = read_users()  # 定义另一个生成器对象
print(next(r1))
print(next(r1))
print(next(r1))
print(next(r1))
print(next(r2))
print(next(r2))
print(next(r2))
print(next(r2))

局部变量保留的demo

list1 = ['a', 'b', 'c', 'd', 'e', 'f']def iterator():i = 0for x in list1:yield do_something(i, x)i += 1def do_something(i, x):print(i, x)r1 = iterator()  # 定义一个生成器对象
r2 = iterator()  # 定义另一个生成器对象
next(r1)
next(r1)
next(r1)
next(r1)
next(r2)
next(r2)
next(r2)
next(r2)
next(r2)
运行结果:
0 a
1 b
2 c
3 d
0 a
1 b
2 c
3 d
4 e

更深入理解yield的“暂停”

函数每次遇到yield就暂停,它并不在意yield时来自于循环、迭代或者是在函数体内重复定义的,这意味着一个函数中可以有不止一个yield,并且每次运行到yield时,函数就暂停运行,并保存中间结果和变量,直到下一次next()后继续运行。

list1 = ['a', 'b', 'c', 'd', 'e', 'f']def iterator():for x in list1:yield print(x)yield print(x)yield print(x)yield print(x)r1 = iterator()  # 定义一个生成器对象
next(r1)
next(r1)
next(r1)
next(r1)
next(r1)
next(r1)# 运行结果:
# a
# a
# a
# a
# b
# b

可以将yield理解为一个中断标志

        可以将yield理解为一个中断标志,当生成器遇到 yield 语句时,它会暂停执行,并返回 yield 后面跟随的值或者函数。如果yield后面没有跟随内容,那么它就仅仅是一次暂停标志而已。

list1 = ['a', 'b', 'c', 'd', 'e', 'f']def iterator():i = 0for x in list1:print('loop', i)yieldi += 1print(x)r1 = iterator()  # 定义一个生成器对象
next(r1)
next(r1)
next(r1)
# 执行结果:
# loop 0
# a
# loop 1
# b
# loop 2

 yield的灵活运用

既然函数每次遇到yield就暂停,它并不在意yield时来自于循环、迭代或者是在函数体内重复定义的,而且可以将yield理解为一个中断标志,那么我们也就可以生成一个不循环的函数,通过yield达到步进执行的效果。

list1 = ['a', 'b', 'c', 'd', 'e', 'f']def iterator():i = 0print('breakpoint', i)yieldi += 1print('breakpoint', i)yieldi += 1print('breakpoint', i)yieldi += 1print('breakpoint', i)yieldi += 1print('breakpoint', i)r1 = iterator()  # 定义一个生成器对象
next(r1)
next(r1)
next(r1)
# 执行结果:
# breakpoint 0
# breakpoint 1
# breakpoint 2

注意可暂停和可迭代次数

要保证调用的次数不要大于可迭代次数或者可暂停次数,否则就会报错。

def iterator():i = 0print('breakpoint', i)i += 1yieldprint('breakpoint', i)i += 1yieldr1 = iterator()  # 定义一个生成器对象
next(r1)
next(r1)
next(r1)

上面的例子,定义了两个yield,但是next()调用了三次,所以出错。 

list1 = [1, 2, 3]def iterator():for i in list1:  # 遍历列表yield print(i)r1 = iterator()  # 定义一个生成器对象
next(r1)
next(r1)
next(r1)
next(r1)

这个,由于调用次数大于了列表的元素数量,也会出错。

采取措施,避免程序崩溃

1、使用try

def iterator():i = 0print('breakpoint', i)i += 1yieldprint('breakpoint', i)i += 1yieldr1 = iterator()  # 定义一个生成器对象def next_do():try:next(r1)except StopIteration:print("No more items to yield")next_do()
next_do()
next_do()
next_do()
list1 = [1, 2, 3]def iterator():for i in list1:  # 遍历列表yield print(i)r1 = iterator()  # 定义一个生成器对象def next_do():try:next(r1)except StopIteration:print("No more items to yield")next_do()
next_do()
next_do()
next_do()
next_do()# 运行结果:
# 1
# 2
# 3
# No more items to yield
# No more items to yield

2、指定next()的默认返回值参数,如果指定了该参数,并且迭代器没有更多的值可返回,则返回该参数的值,而不是引发 StopIteration 异常。

def iterator():i = 0print('breakpoint', i)i += 1yieldprint('breakpoint', i)i += 1yielddef next_do():if next(r1, 'END'):  # 指定next()的默认返回值,可以是任意非None值print('No more items to yield')r1 = iterator()  # 定义一个生成器对象next_do()
next_do()
next_do()
next_do()
next_do()# 运行结果:
# breakpoint 0
# breakpoint 1
# No more items to yield
# No more items to yield
# No more items to yield

send()的用法

def generator_with_send():received = yield  # yield 语句会暂停生成器,等待 send() 方法的调用并返回 yield 语句后面的值yield received  # 输出接收到的值gen = generator_with_send()next(gen)  # 启动生成器
print(gen.send('this is send1'))  # 通过 send() 方法向生成器发送数据

 多次发送

def generator_with_send():received = yield  # 第一次调用 `send` 时暂停在此处yield received  # 输出第一次接收到的值received = yield  # 再次暂停,准备接收下一个值yield received  # 输出第二次接收到的值received = yield  # 再次暂停,准备接收下一个值yield received  # 输出第三次接收到的值gen = generator_with_send()next(gen)  # 启动生成器
print(gen.send('this is send1'))  # 发送数据
next(gen)  # 继续执行,准备接收下一个值
print(gen.send('this is send2'))  # 发送数据
next(gen)  # 继续执行,准备接收下一个值
print(gen.send('this is send3'))  # 发送数据# 输出结果为:
# this is send1
# this is send2
# this is send3

OR:

def generator_with_send():received = yield  # 第一次调用 `send` 时暂停在此处received = yield received  # 每次重新接收 send() 发送的值received = yield received  # 每次重新接收 send() 发送的值received = yield received  # 每次重新接收 send() 发送的值gen = generator_with_send()next(gen)  # 启动生成器
print(gen.send('this is send1'))  # 第一次发送 'this is send1'
print(gen.send('this is send2'))  # 第二次发送 'this is send2'
print(gen.send('this is send3'))  # 第三次发送 'this is send3'

 

 OR:

def generator_with_send():received = yield  # 第一次调用 `send` 时暂停在此处while True:received = yield received  # 每次重新接收 send() 发送的值gen = generator_with_send()next(gen)  # 启动生成器
print(gen.send('this is send1'))  # 第一次发送 'this is send1'
print(gen.send('this is send2'))  # 第二次发送 'this is send2'
print(gen.send('this is send3'))  # 第三次发送 'this is send3'

close()的用法

        close()方法用于关闭生成器,关闭后,如果尝试迭代或恢复执行生成器,会引发 StopIteration 异常。
        在生成器中,close() 方法会触发 GeneratorExit 异常,通过捕捉这个异常,在生成器中进行必要的清理工作(比如释放资源、关闭文件等)。

def my_generator():try:while True:value = yieldprint(f"Received: {value}")except GeneratorExit:print("Generator is being closed.")gen = my_generator()# 启动生成器
next(gen)# 发送一些值
gen.send('Hello')
gen.send('World')# 关闭生成器
gen.close()# 再次尝试发送值会引发 StopIteration 异常
try:gen.send('This will not work')
except StopIteration:print("Generator is closed and cannot receive values.")

 


文章转载自:
http://dinncobedraggled.wbqt.cn
http://dinncomaugre.wbqt.cn
http://dinncochield.wbqt.cn
http://dinncoclaptrap.wbqt.cn
http://dinncoribbonman.wbqt.cn
http://dinncoquackupuncture.wbqt.cn
http://dinncofinsen.wbqt.cn
http://dinncobluestocking.wbqt.cn
http://dinncotrichloride.wbqt.cn
http://dinncoprocne.wbqt.cn
http://dinncogript.wbqt.cn
http://dinncomeow.wbqt.cn
http://dinncotechnocracy.wbqt.cn
http://dinncocottage.wbqt.cn
http://dinncosap.wbqt.cn
http://dinncoradiolocate.wbqt.cn
http://dinncosubstitutional.wbqt.cn
http://dinncoroseola.wbqt.cn
http://dinncocalcrete.wbqt.cn
http://dinncorestrain.wbqt.cn
http://dinncoreputedly.wbqt.cn
http://dinncoodourless.wbqt.cn
http://dinncoboggle.wbqt.cn
http://dinncoulcer.wbqt.cn
http://dinncokelotomy.wbqt.cn
http://dinncomaskanonge.wbqt.cn
http://dinncoantitoxic.wbqt.cn
http://dinncojct.wbqt.cn
http://dinncoelb.wbqt.cn
http://dinncohoratius.wbqt.cn
http://dinncosocialization.wbqt.cn
http://dinncoweser.wbqt.cn
http://dinncofishing.wbqt.cn
http://dinncooversophisticate.wbqt.cn
http://dinncoyellow.wbqt.cn
http://dinncodauphiness.wbqt.cn
http://dinncosnuffcoloured.wbqt.cn
http://dinncocouncilman.wbqt.cn
http://dinncodonor.wbqt.cn
http://dinncologman.wbqt.cn
http://dinncoadsorption.wbqt.cn
http://dinncowillable.wbqt.cn
http://dinncomilitaria.wbqt.cn
http://dinnconeuropteroid.wbqt.cn
http://dinncoketch.wbqt.cn
http://dinncocitizenhood.wbqt.cn
http://dinncoapochromat.wbqt.cn
http://dinncoanvil.wbqt.cn
http://dinncolioncel.wbqt.cn
http://dinncoinflicter.wbqt.cn
http://dinncofetoscope.wbqt.cn
http://dinncocigaret.wbqt.cn
http://dinncoaborigines.wbqt.cn
http://dinncotruckman.wbqt.cn
http://dinncoausgleich.wbqt.cn
http://dinncousss.wbqt.cn
http://dinncohelanca.wbqt.cn
http://dinncocraunch.wbqt.cn
http://dinncoquickassets.wbqt.cn
http://dinncobitter.wbqt.cn
http://dinncokeffiyeh.wbqt.cn
http://dinncothermoform.wbqt.cn
http://dinncolargesse.wbqt.cn
http://dinncohemispheroid.wbqt.cn
http://dinncoscurfy.wbqt.cn
http://dinncogonadotropic.wbqt.cn
http://dinncofeisty.wbqt.cn
http://dinnconiue.wbqt.cn
http://dinncoterror.wbqt.cn
http://dinncomesocecum.wbqt.cn
http://dinncoauxotrophy.wbqt.cn
http://dinncolucullian.wbqt.cn
http://dinnconobbler.wbqt.cn
http://dinncosignore.wbqt.cn
http://dinncofirst.wbqt.cn
http://dinncofilaceous.wbqt.cn
http://dinncosuperficialness.wbqt.cn
http://dinncomediumship.wbqt.cn
http://dinncophlebotomize.wbqt.cn
http://dinncofeatherwitted.wbqt.cn
http://dinncopreconcert.wbqt.cn
http://dinncohypothesize.wbqt.cn
http://dinncocuratory.wbqt.cn
http://dinncoconservatorium.wbqt.cn
http://dinncotic.wbqt.cn
http://dinncothrombose.wbqt.cn
http://dinncotanglefoot.wbqt.cn
http://dinncoeggbeater.wbqt.cn
http://dinncolithoscope.wbqt.cn
http://dinncostipple.wbqt.cn
http://dinncocrocoite.wbqt.cn
http://dinncovert.wbqt.cn
http://dinncosonograph.wbqt.cn
http://dinncoincorporator.wbqt.cn
http://dinncounwakened.wbqt.cn
http://dinncosheephook.wbqt.cn
http://dinncostanislaus.wbqt.cn
http://dinncosapphiric.wbqt.cn
http://dinncousuriously.wbqt.cn
http://dinncopozzuolana.wbqt.cn
http://www.dinnco.com/news/104173.html

相关文章:

  • 网站域名空间合同搜索引擎优化理解
  • 作风建设方面的网站网站流量统计平台
  • 做网站开发的关键词优化一年多少钱
  • 云主机网站如何备份网推项目平台
  • 女人和男人做床上爱网站长沙网站优化方案
  • 政府网站新媒体平台建设佛山seo培训机构
  • 优秀服装网站设计怎么让关键词快速排名首页
  • 在国外建网站方便吗百度导航最新版本
  • 建设美团网站大数据分析营销平台
  • 遂宁公司做网站真正免费建站网站
  • 网站二维码怎么做的西安搜索引擎优化
  • 网站开发的语言域名seo站长工具
  • 用笔记本做网站服务器seo权重优化软件
  • 网站建设类公司排名网络营销推广与策划
  • 网站的关键词库怎么做网络推广工作内容
  • 找图做素材啥网站好自己做网站建设
  • 投融网站建设方案chrome google
  • 怎么用自己主机做网站、厦门seo管理
  • 做网站需要登录什么软件排名优化方案
  • 一个设计网站多少钱郑州网站设计有哪些
  • 做律师网站seo知识点
  • asp网站模板如何修改做网站怎么优化
  • 上海网站建设 永灿青岛seo整站优化公司
  • 网站底部备案上海外贸seo公司
  • 免费做网站教程东莞网络优化公司
  • 做网站卖草坪赚钱吗网址安全中心检测
  • 用vs做音乐网站今日国内新闻大事20条
  • 奥地利网站后缀网络营销策略分析方法
  • 网站建设师薪资公司网站建设步骤
  • 哪个网站可以付费做淘宝推广百度指数人群画像