yield and generator in python

server/2024/10/21 7:57:06/

首先,假设大家都对于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/server/95399.html

相关文章

同一窗口还是新窗口打开链接更利于SEO优化

💝💝💝欢迎莅临我的博客,很高兴能够在这里和您见面!希望您在这里可以感受到一份轻松愉快的氛围,不仅可以获得有趣的内容和知识,也可以畅所欲言、分享您的想法和见解。 推荐:「storm…

cocos creator绘制网格背景(基于矢量绘图)

在2D游戏开发中,设计2D地图的背景实现通常有以下几种方式: 静态背景图: 最简单的方式是使用静态背景图,即将整个背景作为一个静态图像加载到游戏中。这种方式适用于简单的游戏或者背景不需要变化的场景。 平铺背景图:…

24.8.3数据结构|双向循环链表、静态链表

双向循环链表 节点类型与双链表的节点类型完全相同双向循环链表的操作也与双链表的操作基本一致。 例题 将自然数一到N按由小到大的顺序沿顺时针方向围成一个圈,然后以一为起点先沿顺时针方向数到第N个数将其划去,再沿逆时针方向数到第K个数将其滑去&a…

JS 原型和原型链

构造函数 封装是面向对象思想中比较重要的一部分,js 面向对象可以通过构造函数实现的封装。 同样的将变量和函数组合到了一起并能通过 this 实现数据的共享,所不同的是 JS 借助构造函数创建出来的实例对象之间是彼此不影响的 存在浪费内存的问题&#…

网络基础命令配置复习 (基础华为设备)

目录 一.前言 二.Telnet远程登陆 2.1telnet介绍 2.2telnet的配置 三.交换机基础配置 四.致谢 一.前言 网络基础不仅是IT从业者的必备知识,也是日常生活中使用网络的人们应该了解的内容。通过学习和掌握这些基础知识,你将能更好地理解和利用现…

RocketMQ5.0消费者

RocketMQ 5.0 提供了三种主要的消费者类型:PushConsumer、SimpleConsumer 和 PullConsumer。每种类型的消费者都有其特定的使用场景和特点。以下是对这三种消费者的概念及其区别的详细阐述: PushConsumer 概念: PushConsumer 是一种主动推送…

Github 2024-08-03 Rust开源项目日报 Top10

根据Github Trendings的统计,今日(2024-08-03统计)共有10个项目上榜。根据开发语言中项目的数量,汇总情况如下: 开发语言项目数量Rust项目10HTML项目1Go项目1Meilisearch: 快速搜索API,提升工作效率 创建周期:2252 天开发语言:Rust协议类型:MIT LicenseStar数量:44442 …

北京汽车美容元宇宙:数字化浪潮下的车美服务新革命

随着社会的发展和科技的进步,元宇宙这一概念正逐步渗透到人们的生活之中,改变了传统行业的运作模式。北京,作为科技创新的前沿城市,正见证着汽车美容元宇宙的诞生与兴盛,为车主们带来了全新的服务体验和便利。 ### 正…