首页 > 编程语言 >Python - Generators

Python - Generators

时间:2024-07-31 11:17:34浏览次数:10  
标签:__ iterator generator Python object next Generators expression

The task of implementing iterators can be simplified by using generators. We have seen how to create custom iterators using the object-oriented way, i.e., by defining a class that has __init__, __next__, and __iter__ methods. For example, we saw the Cubes class which when instantiated created an iterator object that gave out cubes of numbers. These types of simple iterators can be implemented in a much easier way by writing generators.

There are two types of generators: generator functions and generator expressions. Both of them are used to create generator objects which are actually iterators. A generator object is a kind of iterator, and we get a generator object by writing a generator function or a generator expression.

When you write a generator, you do not need to worry about writing the __iter__ and __next__ methods. You get the iterator interface automatically. So, when you want to get an iterator without writing a class, you can write generators. In fact, writing a class to define your own iterator is very rare. Generally, the automated syntax of generators is preferred to get your own iterators. However, if you need to create complex iterators or need to give access to some extra attributes and methods, then you will have to write class-based iterators.

>>> def cubes(start, stop):

...         for n in range(start, stop+1):

...             yield n * n * n

>>> y = cubes(2, 5)

Right now, do not worry about what is written inside the function. What you need to understand is that when we call this function, it returns a generator object, which is actually an iterator.

>>> y

<generator object cubes at 0x000001E3263A75B0>

>>> y is iter(y)

True

By writing this generator function, we were able to get an iterator without worrying about any of the methods needed to satisfy the iterator protocol. They are automatically implemented for us.

We can use the next function to get values from this generator object.

>>> next(y)

8

>>> next(y)

27

>>> next(y)

64

>>> next(y)

125

>>> next(y)

StopIteration

The calls to next function give us the cubes, and the StopIteration error was raised to signify the end of data. This generator object y behaves just like the iterator object x (instance of Cubes) would have behaved.

 

Generator expression is an expression that returns an iterator also known as generator object. This generator object returns values one by one when used in an iteration context such as for loop.

Generator expressions are syntactically almost similar to list comprehensions, but the difference is that generator expressions return a generator object instead of a list. Generator objects generate one value at a time, while the comprehensions save all the values in memory. This is why generator expressions consume less memory as compared to comprehensions, and there is no waiting time as all the values are not computed at once. The saving in memory and time is crucial when the number of data values is very large. Let us see an example:

>>> (n * n * n for n in range(2, 6))

<generator object <genexpr> at 0x000001F5FD451E70>

This is an example of a generator expression. We know that list comprehensions are enclosed in square brackets, while set and dictionary comprehensions are enclosed in curly braces and we do not have anything like tuple comprehensions, so when we have a comprehension like expression enclosed in parentheses, it is a generator expression. This generator expression gives us a generator object which is lazily evaluated, and it can be iterated over.

>>> g = (n * n * n for n in range(2, 6))

>>> g

<generator object <genexpr> at 0x000001F5FF58B1B0>

g is a generator object, let us call next function for it.

>>> next(g)

8

>>> next(g)

27

>>> next(g)

64

>>> next(g)

125

>>> next(g)

StopIteration

Now it is exhausted, so we cannot use it again.

 

>>> for i in (n * n * n for n in range(2, 6) if n % 2 == 0):

...  print(i)

Generator expressions are written inside parentheses. If you are writing the generator expression as a single argument to a function call, then the parentheses of the function call are sufficient, there is no need to write 2 pairs of parentheses, one for the call and other for the generator expression. But if there are more than one argument, then you need to enclose the generator expression in parentheses otherwise you will get a syntax error.

For example, in the following function call, we have sent a generator expression as argument.

>>> func(n * n for n in range(2,4))

Since this is the only argument, the parentheses are not required. If we have more arguments, then we will have to put the parentheses.

func((n*n for n in range(2,4)), 'x')

 

标签:__,iterator,generator,Python,object,next,Generators,expression
From: https://www.cnblogs.com/zhangzhihui/p/18334236

相关文章

  • Python应用—加密、解密文件
    1.创作需求日常生活中我们有很多文件想要保密。这个脚本可以方便大家对所有的文件类型进行加密,解密。最大程度保护我们的隐私。2.话不多说,直接上代码fromcryptography.fernetimportFernetimportdocx#加密defencrypt_file(filename):#生成密钥key=Fer......
  • 三种语言实现二维前缀和(C++/Python/Java)
    题目输入一个n行m列的整数矩阵,再输入q个询问,每个询问包含四个整数x1,y1,x2,y2表示一个子矩阵的左上角坐标和右下角坐标。对于每个询问输出子矩阵中所有数的和。输入格式第一行包含三个整数n,m,q接下来n行,每行包含m个整数,表示整数矩阵。接下来q行,每行包含四个整数......
  • Python rocketMq 客户端的同步和异步模式
    同步模式fromrocketmq.clientimportPushConsumer,ConsumeStatusimporttimedefcallback(msg):print(msg.id,msg.body,msg.get_property('property'))returnConsumeStatus.CONSUME_SUCCESSdefstart_consume_message():consumer=PushCon......
  • python中元组的学习
    元组目录元组元组的概念元组操作元组的常用方法元组的遍历元组的概念Tuple(元组)与列表相似,不同之处遭遇元组的元素不能修改元组表示多个元素组成的序列用于储存一串信息,数据之间使用,分隔元组用()定义#元组的创建info_tuple=("zhangsan",18,1.75)info_tuple2=(1,)#......
  • 尝试通过Python访问.zip文件中的.gz文件
    我有一个包含大量.gz文件的.zip文件,我需要对其进行处理。我想打开.zip,我可以通过以下代码轻松完成:zf=zipfile.ZipFile("file.zip","r")forgzfileinzf.filelist:withgzip.GzipFile(fileobj=zf.open(gzfile.filename,"r"),mode="r")asf:df......
  • python导入包报错ImportError: cannot import name ‘Protocol‘
    python32.pyTraceback(mostrecentcalllast):File"2.py",line5,in<module>importptwt#use"fromsrcimportptwt"foraclonedtherepoFile"……lib/python3.6/site-packages/ptwt/_util.py",line2......
  • Python - Creating your own Iterator
    Inourfirstexample,wewillcreateiterableobjects,which,wheniteratedover,willgiveoutcubesofnumbers,andtheseobjectswillsupportmultipleiterations.classCubes:def__init__(self,start,stop):self.start=startsel......
  • 三种语言实现前缀和(C++/Python/Java)
    题目输入一个长度为n的整数序列。接下来再输入m个询问,每个询问输入一对l,r对于每个询问,输出原序列中从第l个数到第r个数的和。输入格式第一行包含两个整数n和m。第二行包含n个整数,表示整数数列。接下来m行,每行包含两个整数l和r,表示一个询问的区间范围。......
  • Python - 旨在通过命令提示符执行数据清理,但代码似乎无法运行
    我从一位同事那里收到了这段代码,我打算用它来处理100csv文件以提取有关粒子的值。代码如下所示:importsysimportcsv#Usage#skdata_decode.py[inputfile1][inputfile2]...#(Itispossibletousefiledcardtospecifyinputfiles.)##l......
  • 如何在 python 终端中的 x,y 位置上书写(基于文本)
    我想在python(基于文本)的终端中的定义位置(x,y)上写入字符。假设,我有一个大小为25x80的终端,并且想要在位置(2,20)上写入字符。我可以在Python中执行此操作吗?现在,我使用25x80数组,并写入该数组。为了在屏幕上显示,我清除屏幕并将该数组的全部内容写入屏幕,但这效......