python迭代器

Good day learners! In our previous tutorial, we learned about Python Operator Overloading. In this tutorial we are going to learn about Python Iterator.

美好的一天学习者! 在上一教程中,我们了解了Python操作符重载 。 在本教程中,我们将学习Python Iterator。

Python迭代器 (Python Iterator)

Knowingly or unknowingly, you have used iterator in your Python code. Basically, an iterator is an object which is used to iterate through an iterable element. Didn’t understand the meaning of the last line? Well, don’t worry. We will make you understand about Python Iterator through our tutorial.

在有意无意的情况下,您已经在Python代码中使用了迭代器。 基本上,迭代器是用于迭代可迭代元素的对象。 不明白最后一行的意思吗? 好吧,别担心。 我们将通过本教程使您了解Python Iterator。

Python迭代器和可迭代元素 (Python Iterator and Iterable Elements)

Most of the objects of Python are iterable. In python, all the sequences like Python String, Python List, Python Dictionary etc are iterable. Now, what is iterator? Suppose, A group of 5 boys are standing in a line. Your are pointing at the first boy and ask him about his name. Then, he replied. After that, you ask the next boy and so on. The below picture will illustrate the thing.

Python的大多数对象都是可迭代的。 在python中,所有序列(如Python String , Python List , Python Dictionary等)都是可迭代的。 现在,什么是迭代器? 假设有5个男孩在排队。 您指着第一个男孩,问他这个名字。 然后,他回答。 之后,您询问下一个男孩,依此类推。 下图将说明问题。

In this case, you are the Iterator!!!! Obviously, the group of boys is the iterable element. Hope you understand now.

在这种情况下,您就是Iterator !!!! 显然,男孩组是可迭代的元素。 希望你现在明白了。

Python迭代器协议 (Python Iterator Protocol)

Python Iterator Protocol includes two functions. One is iter() and the other is next(). In this section, we will learn to how to traverse an iterable element using Python Iterator Protocol.

Python迭代器协议包含两个函数。 一个是iter() ,另一个是next() 。 在本节中,我们将学习如何使用Python迭代器协议遍历可迭代元素。

In the previous section, we gave the example of group of 5 boys and you. You are the iterator and the boys group is the iterable element. After knowing the name of one boy, you ask the same question to the next boy.

在上一节中,我们给出了一个由5个男孩和您组成的小组的示例。 您是迭代器,而boys组是可迭代的元素。 知道一个男孩的名字后,您向下一个男孩问同样的问题。

After that, you do it again. iter() function is used to create an iterator of an iterable element. And the next() function is used to iterate to the next element.

在那之后,您再做一次。 iter()函数用于创建可迭代元素的迭代器。 next()函数用于迭代到下一个元素。

Python迭代器示例 (Python Iterator Example)

If the iterator go beyond the number of iterable elements then the next() method will raise StopIteration exception. See the code below for python iterator example.

如果迭代器超出了可迭代元素的数量,则next()方法将引发StopIteration异常。 有关python迭代器示例,请参见下面的代码。

list_string = ['Boy 1', 'Boy 2', 'Boy 3', 'Boy 4', 'Boy 5']iterator_you = iter(list_string)# point the first boy
output = next(iterator_you)
# This will print 'Boy 1'
print(output)# point the next boy, the second boy
output = next(iterator_you)
# This will print 'Boy 2'
print(output)# point the next boy, the third boy
output = next(iterator_you)
# This will print 'Boy 3'
print(output)# point the next boy, the fourth boy
output = next(iterator_you)
# This will print 'Boy 4'
print(output)# point the next boy, the fifth boy
output = next(iterator_you)
# This will print 'Boy 5'
print(output)# point the next boy, but there is no boy left
# so raise 'StopIteration' exception
output = next(iterator_you)
# This print will not execute
print(output)

Output

输出量

Boy 1
Boy 2
Boy 3
Boy 4
Boy 5
Traceback (most recent call last):File "/home/imtiaz/Desktop/py_iterator.py", line 32, in output = next(iterator_you)
StopIteration

制作Python迭代器 (Making of a Python Iterator)

However, you can make your own specified Python Iterators. To do so, you have to implement a Python class. I assume that you know about Python Class. If you don’t know about this, you can read our tutorial about Python Class.

但是,您可以创建自己的指定Python迭代器。 为此,您必须实现一个Python类。 我假设您了解Python类。 如果您不了解这一点,可以阅读有关Python Class的教程。

As we have said earlier that, Python Iterator Protocol consist of two methods. So we need to implement those method.

如前所述,Python迭代器协议包含两种方法。 因此,我们需要实现那些方法。

For example, you want to generate a list of fibonacci number so that each time call the next function it returns you the next fibonacci number.

例如,您要生成一个斐波那契编号列表,以便每次调用下一个函数时,它都会向您返回下一个斐波那契编号。

To raise the exception, we limit the value of n below 10. If the value of n reach 10, it will raise an exception. The code will be like this.

为了引发异常,我们将n的值限制为小于10。如果n的值达到10,它将引发异常。 代码将像这样。

class fibo:def __init__(self):# default constructorself.prev = 0self.cur = 1self.n = 1def __iter__(self):  # define the iter() functionreturn selfdef __next__(self):  # define the next() functionif self.n < 10:  # Limit to 10# calculate fibonacciresult = self.prev + self.curself.prev = self.curself.cur = resultself.n += 1return resultelse:raise StopIteration  # raise exception# init the iterator
iterator = iter(fibo())
# Try to print infinite time until it gets an exception
while True:# print the value of next fibonacci up to 10th fibonaccitry:print(next(iterator))except StopIteration:print('First 9 fibonacci numbers have been printed already.')break  # break the loop

So, the output will be

因此,输出将是

1
2
3
5
8
13
21
34
55
First 9 fibonacci numbers have been printed already.

为什么要制作Python迭代器 (Why Making Python Iterator)

After going through the previous section, a question may arise to your mind that why should we make Python Iterator.

经过上一节后,您可能会想到一个问题,为什么我们应该制作Python Iterator。

Well, we have seen already that iterator can traverse an iterable element. Suppose, in our previous example if we make a list of fibonacci numbers and then traverse it via a Python Iterator, it would take huge memory. But if you create a simple Python Iterator class, you can serve your purpose without consuming that much memory.

好了,我们已经看到迭代器可以遍历可迭代元素。 假设在前面的示例中,如果我们列出了斐波那契数字的列表,然后通过Python迭代器遍历它,则将占用大量内存。 但是,如果您创建一个简单的Python Iterator类,则可以在不消耗大量内存的情况下实现您的目的。

So that’s all for Python Iterator. Hope that you are now able to work with Python Iterator. For any further query, you can use the comment box. Learn and practice as much as you can.

这就是Python Iterator的全部内容。 希望您现在可以使用Python Iterator。 对于任何其他查询,您可以使用注释框。 尽可能多地学习和练习。

#HappyCoding

#HappyCoding

Reference: Python Doc

参考: Python文档

翻译自: https://www.journaldev.com/14620/python-iterator

python迭代器

python迭代器_Python迭代器相关推荐

  1. python列表迭代器_python迭代器生成器-迭代器和list区别

    迭代 生成 for循环遍历的原理 for循环遍历的原理就是迭代,in后面必须是可迭代对象 为什么要有迭代器 对于序列类型:字符串.列表.元组,我们可以使用索引的方式迭代取出其包含的元素.但对于字典.集 ...

  2. pythonzip是迭代器_Python迭代器和zip

    迭代器就像一个项目流.您只能一次查看流中的项目,并且只能访问第一个元素.要查看流中的某些内容,您需要将其从流中删除,一旦您从流的顶部获取内容,它就会从流中消失. 当您调用zip(i,i)时,zip首先 ...

  3. python迭代器使用_python迭代器的使用方法实例

    什么是迭代器?迭代器是带有next方法的简单对象,当然也要实现__iter__函数.迭代器能在一序列的值上进行迭代,当没有可供迭代时,next方法就会引发StopIteration 的异常.pytho ...

  4. rust python对比_Python Rust 迭代器对比

    迭代是数据处理的基石,而 Python 中所有集合都可以迭代,这是 Python 让使用者感到非常方便的特征之一. 下面是一些在 Python 中经常使用的迭代模式 # 列表 for i in [1, ...

  5. python中迭代器有哪些_Python迭代器:什么是Python中的迭代器以及如何使用它?

    Python编程语言已经扩展了创新的每一个方面,包括机器学习.数据科学.人工智能等,这些概念是Python作为编程语言取得成功的基石.在本文中,我们将通过以下概念来理解Pytho Python编程语言 ...

  6. python平方数迭代器_Python三大神器之迭代器详解

    我们将要来学习python的重要概念迭代和迭代器,通过简单实用的例子如列表迭代器和xrange. 可迭代 一个对象,物理或者虚拟存储的序列.list,tuple,strins,dicttionary, ...

  7. python生成器迭代器_python 生成器 迭代器

    阅读目录 一 递归和迭代 二 什么是迭代器协议 三 python中强大的for循环机制 四 为何要有for循环 五 生成器初探 六 生成器函数 七 生成器表达式和列表解析 八 生成器总结 一 递归和迭 ...

  8. python模板引擎传迭代器_python之路 模块,序列化,迭代器,生成器

    一.模块 1.模块简介 模块是一个包含所有你定义的函数和变量的文件,其后缀名是.py.模块可以被别的程序引入,以使用该模块中的函数等功能.这也是使用python标准库的方法. 类似于函数式编程和面向过 ...

  9. python 迭代器 生成器_Python迭代器和生成器

    迭代器认知 迭代器 (iterator): 如果一个对象同时有__iter__()和__next__()魔术方法的话,这个对象就可以称为是迭代器. __iter__()的作用是可以让for循环遍历.而 ...

最新文章

  1. [置顶] Hibernate从入门到精通(十)多对多单向关联映射
  2. python 设置 初始值_Python初始值表示为无穷大
  3. windows 2003几个优化技巧
  4. Boost:双图bimap与mi_hashed indices索引的测试程序
  5. phpmyadmin 4.8.1 Remote File Inclusion(CVE-2018-12613)远程文件包含漏洞复现
  6. mybatis错误之配置文件属性配置问题
  7. vue mock模拟后台接口数据
  8. qt编译器5.12.3怎么一次性删除所有的断点
  9. Spring和Mybatis整合
  10. selenium+java:获取列表中的值
  11. java课堂作业(四)
  12. C语言中各数据类型和他们对应的最大值和最小值的常量
  13. 浅谈JS中的原型对象和原型链
  14. APFNet训练+测试复现过程记录
  15. 奥西450的服务器系统,奥西TDS450驱动
  16. java-nio网络编程
  17. 消息推送技术干货:美团实时消息推送服务的技术演进之路
  18. ROS中的Client Library与roscpp talker lisener
  19. No converter for [class XXX] with preset Content-Type ‘null‘
  20. Javascript 历史遗留 - 产生的语法问题整理

热门文章

  1. SQL 递归树 子父节点相互查询
  2. [代码]获取源页的控件值
  3. [转载] python hex转字符串_Python hexstring-list-str之间的转换方法
  4. [转载] numpy功能快速查找
  5. [转载] Python 完整实现的简单遗传算法(SGA)
  6. [转载] Python-科赫雪花(科克曲线)
  7. [转载] 用Python进行简单的文本相似度分析
  8. [转载] 使用Python防止SQL注入攻击
  9. [转载] Python进程——multiprocessing.Event()|Barrier()
  10. Vue.js 学习笔记 四 用一,二,三的知识做个跑马灯