yield and generator in python

embedded/2024/9/23 3:48:34/

首先,假设大家都对于pytyhon的List comprehension的使用有了一定经验(它可以用于list,set,和dict哦)

不熟悉的参考介绍: Comprehending Python’s Comprehensions – dbader.org

generator

generator是哦嗯一种返回lazy iterator的特殊类型函数。list comprehensions return full lists, while generator expressions return generators.

如下面代码,分别使用list和generator的构造,但是两者所占据的内存大家却完全不一样。

>>> import sys
>>> nums_squared_lc = [i ** 2 for i in range(10000)]
>>> sys.getsizeof(nums_squared_lc)
87624
>>> nums_squared_gc = (i ** 2 for i in range(10000))
>>> print(sys.getsizeof(nums_squared_gc))
120

 generator functions are a special kind of function that return a lazy iterator. These are objects that you can loop over like a list. However, unlike lists, lazy iterators do not store their contents in memory.

python中,通过“类似list comprehension”或者yield的使用,我们可以构造generator并调用。

yield

yield的作用介绍如下,当使用generator的特殊方法,比如next()时,generator中的代码会被执行到yield,当经过yield时,python中generator的执行会被中断,函数的当前状态会被保存,直到下一次执行。 

下列函数是yield的一个经典用法。

def infinite_sequence():num = 0while True:yield numnum += 1

在调用该函数的过程中,每一次,输出的数会增加1,相比于return,yield会保存function当前的状态,参考How to Use Generators and yield in Python – Real Python

On the whole, yield is a fairly simple statement. Its primary job is to control the flow of a generator function in a way that’s similar to return statements. As briefly mentioned above, though, the Python yield statement has a few tricks up its sleeve.

When you call a generator function or use a generator expression, you return a special iterator called a generator. You can assign this generator to a variable in order to use it. When you call special methods on the generator, such as next(), the code within the function is executed up to yield.

When the Python yield statement is hit, the program suspends function execution and returns the yielded value to the caller. (In contrast, return stops function execution completely.) When a function is suspended, the state of that function is saved. This includes any variable bindings local to the generator, the instruction pointer, the internal stack, and any exception handling.

This allows you to resume function execution whenever you call one of the generator’s methods. In this way, all function evaluation picks back up right after yield. You can see this in action by using multiple Python yield statements:

 

 When you use next(), Python calls .__next__() on the function you pass in as a parameter. There are some special effects that this parameterization allows, but it goes beyond the scope of this article. Experiment with changing the parameter you pass to next() and see what happens!


http://www.ppmy.cn/embedded/90266.html

相关文章

分享c语言中一些实用的函数2

目录 一.头文件 1.sqrt()函数 2.sin&#xff0c;cos&#xff0c;tan函数 附加:宏定义π 3.exp函数 4.fabs函数 5.fmax函数 6.floor函数 7.log函数 附加&#xff1a;求一个数是几为数(运用floor函数和log函数) 8.pow函数 二.头文件 1.abs函数 附加: 一.头文件<…

python常用库

目录 tqdm库介绍用法 argparse库介绍用法 tqdm库 介绍 封装一个可视化&#xff0c;可拓展的进度条&#xff0c;以了解项目运行的时长&#xff0c;了解项目进展情况。 传入第 用法 安装 pip install tqdm1直接使用 for i in tqdm(range(1000)):time.sleep(0.01)等价 for i…

消息队列RabbitMQ部分知识

1.简述RabbitMQ的架构设计 RabbitMQ 是一个开源的消息代理&#xff0c;采用了高级消息队列协议&#xff08;AMQP&#xff09;&#xff0c;其架构设计主要包括以下几个关键组件和概念&#xff1a; 1.消息生产者&#xff08; Producer&#xff09;&#xff1a; 负责发送消息到…

5.6软件工程-运维

运维 系统转换系统维护系统评价练习题 系统转换 新老系统的转换 系统转换是指&#xff1a;新系统开发完毕&#xff0c;投入运行&#xff0c;取代现有系统的过程&#xff0c;需要考虑多方面的问题&#xff0c;以实现与老系统的交接&#xff0c;有一下三种转换计划&#xff1a; …

npm创建vue的ts项目

一、进入项目文件夹 使用cmd进入你想要创建项目的文件夹&#xff0c;此处为 E盘的test文件夹 cd E:\testE:二、创建项目 此处项目名为 MyTestProject npm create vitelatest输入上述代码&#xff0c;回车后会出现灰色的虚拟名称&#xff0c;此处输入你自己的名称即可&#…

phpMyAdmin 漏洞

一、日志文件拿shell 在sql语句执行界面执行命令 将日志功能打开 再次查看 更改日志保存路径 擦看是否更改成功 植入一句话木马 访问木马 使用工具连接 二、导⼊导出拿WebShell 判断网站位置 判断在www在Extensions同级 写shell 访问shell,使用工具连接 三、可视化界面getshe…

逻辑推理之lora微调

逻辑推理微调 比赛介绍准备内容lora微调lora微调介绍lora优势代码内容 start_vllm相关介绍调用 运行主函数提交结果总结相应连接 比赛介绍 本比赛旨在测试参与者的逻辑推理和问题解决能力。参与者将面对一系列复杂的逻辑谜题&#xff0c;涵盖多个领域的推理挑战。 比赛的连接:…

OpenHarmony应用开发和Android应用开发区别

OpenHarmony 和 Android 是两个不同的操作系统平台&#xff0c;各自有其独特的开发环境和架构。以下是 OpenHarmony 应用开发与 Android 应用开发之间的主要区别&#xff1a; 1. 架构设计 OpenHarmony 微内核架构&#xff1a;OpenHarmony 采用微内核设计&#xff0c;核心功…