zoukankan      html  css  js  c++  java
  • Python之迭代器

    本文通过文章同步功能推送至博客园,显示排版可能会有所错误,请见谅!

    迭代器指对象提供了一个next方法,执行该方法要么放回迭代中的下一项,要么就引起一个Stopitertion错误,以终止迭代。

    可迭代对象则是内部定义了一个__iter__()方法以实现迭代器协议的对象。 从迭代器定义上来,所有迭代器都应有next方法。可迭代对象并非迭代器,本质上,可迭代对象(如字符串、列表、元组、集合、字典、文件等)内部提供了一个__iter__()方法,使用__iter__()方法能将其转化为一个迭代器,进而支持next方法用于迭代。

    在python中,for循环、sum、map和filter等函数实质上是使用迭代器协议。如for循环,接受一个可迭代对象,在实际处理时,先使用可迭代对象的__iter__()方法获得一个迭代器,然后在使用next方法迭代,直到返回最后一个值,for内置了处理Stopitertion错误的机制。

    for i in list(range(101)):
        print(i)

    上述for循环简单模拟处理如下:

    Iter = range(101).__iter__()
    while True:
        try:
            i = Iter.__next__()
            print(i)
        except Stopitertion:
            break
    

    迭代器可以使用3种方式迭代

    使用send()方法时,可以传入一个值给当前yield

    知道了迭代器的特性,我们可以使用迭代器简单模拟实现一个列表对象的索引功能!

    class LIST(list):
        '''新建一个LIST类,继承list类'''
        def find(self,n):
            """find方法用于索引取值"""
            i = 0
            iter = self.__iter__()     #将可迭代对象列表转为迭代器赋值给iter
            res = next(iter)           #使用迭代器的next方法
            while i != n:              #当计数器i不等于目标索引n时,使用next迭代
                res = next(iter)
                i += 1
            return res
    num_list=LIST(i for i in range(100))       #定义一个LIST类的对象
    res = num_list.find(50)            #调用LIST类中的find方法,取得索引号50的值
    print(res)    #res = 50
    

  • 相关阅读:
    当Django模型迁移时,报No migrations to apply 问题时
    django--各个文件的含义
    django--创建项目
    1013. Battle Over Cities (25)
    1011. World Cup Betting (20)
    1009. Product of Polynomials (25)
    1007. Maximum Subsequence Sum (25)
    1006. Sign In and Sign Out (25)
    1008. Elevator (20)
    1004. Counting Leaves (30)
  • 原文地址:https://www.cnblogs.com/lazyfish007/p/11487613.html
Copyright © 2011-2022 走看看