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

    作者博文地址:https://www.cnblogs.com/liu-shuai/

    概述

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

    延迟计算或惰性求值 (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()方法。

  • 相关阅读:
    How to build Linux system from kernel to UI layer
    Writing USB driver for Android
    Xposed Framework for Android 8.x Oreo is released (in beta)
    Linux Smartphone Operating Systems You Can Install Today
    Librem 5 Leads New Wave of Open Source Mobile Linux Contenders
    GUADEC: porting GNOME to Android
    Librem 5 – A Security and Privacy Focused Phone
    GNOME and KDE Join Librem 5 Linux Smartphone Party
    Purism计划推出安全开源的Linux Librem 5智能手机
    国产系统之殇:你知道的这些系统都是国外的
  • 原文地址:https://www.cnblogs.com/liu-shuai/p/6098234.html
Copyright © 2011-2022 走看看