zoukankan      html  css  js  c++  java
  • Python迭代器(Iterator)

    概述

      迭代器是访问集合元素的一种方式。迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退。

    延迟计算或惰性求值 (Lazy evaluation)

      迭代器不要求你事先准备好整个迭代过程中所有的元素。仅仅是在迭代至某个元素时才计算该元素,而在这之前或之后,元素可以不存在或者被销毁。这个特点使得它特别适合用于遍历一些巨大的或是无限的集合。

    可迭代对象

      迭代器提供了一个统一的访问集合的接口。只要是实现了__iter__()或__getitem__()方法的对象,就可以使用迭代器进行访问。

      序列:字符串、列表、元组

      非序列:字典、文件

      自定义类:用户自定义的类实现了__iter__()或__getitem__()方法的对象

    创建迭代器对象

      使用内建的工厂函数iter(iterable)可以获取迭代器对象:

      语法:

        iter(collection) -> iterator

        iter(callable,sentinel) -> iterator

      说明:

        Get an iterator from an object. 

        In the first form, the argument must supply its own iterator, or be a sequence.

        In the second form, the callable is called until it returns the sentinel.

      实例展示:

     1 使用对象内置的__iter__()方法生成迭代器
     2 >>>L1 = [1,2,3,4,5,6]
     3 >>>I1 = L1.__iter__()
     4 >>>print I1
     5 <listiterator object at 0x7fe4fd0ef550>
     6 >>> I1.next()
     7 1
     8 >>> I1.next()
     9 2
    10 >>> I1.next()
    11 3
     1 使用内置工厂函数生成迭代器
     2 >>> L1 = [1,2,3,4,5,6]
     3 >>> I2 = iter(L1)
     4 >>> print I2
     5 <listiterator object at 0x7fe4fd0ef610>
     6 >>> I2.next()
     7 1
     8 >>> I2.next()
     9 2
    10 >>> I2.next()
    11 3

    说明:

      for循环可用于任何可迭代对象

      for循环开始时,会通过迭代协议传输给iter()内置函数,从而能够从迭代对象中获得一个迭代器,返回的对象含有需要的next()方法。

    http://www.cnblogs.com/spiritman/
  • 相关阅读:
    assignment of day nine
    不会互相转化,看我的
    enumrate用法
    这是作业
    这是表格
    本周回顾
    爬虫
    今天又学了啥?
    what have we learnt in day five
    OMG that's another blog!
  • 原文地址:https://www.cnblogs.com/spiritman/p/5158331.html
Copyright © 2011-2022 走看看