zoukankan      html  css  js  c++  java
  • python(15)——迭代和迭代器

    #迭代:通过for循环遍历对象的每一个元素的过程
    #可迭代的数据类型:
    '''
    list
    tuple
    dict
    set
    string
    bytes
    '''
    #判断对象是否可以迭代?——》collections模块的Iterable类型来判断

    from collections import Iterable
    #字符串
    result = isinstance('abc',Iterable)
    print(result)
    #列表/元组
    result=isinstance([1,2,3],Iterable)
    print(result)
    #字典
    result=isinstance({'a':'A','b':'B'},Iterable)
    print(result)
    #集合
    result=isinstance((1,2,3,4),Iterable)
    print(result)
    
    #整数是否可迭代
    result=isinstance(123,Iterable)
    print(result)

    #迭代器
    '''
    1.迭代器是一种可以被遍历的对象,并且能作用于next()函数
    2.迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问结束
    3.迭代器只能往后遍历不能回溯(列表可以取前面数据,也可以取后面的数据)
    4.迭代器通常要实现的两个基本方法:iter()和next()
    #iter()创建迭代器对象
    #next()获取迭代器的下一个元素,当后面没有元素可以获取的时候,弹出错误StopIteration

    '''

    #字符串,列表或元组对象,甚至自定义对象都可以用于创建迭代器
    lis=[1,2,3,4]
    #使用python内置的iter()方法创建迭代器对象
    it=iter(lis)
    print(it)
    
    #使用next()方法获取迭代器的下一个元素
    result =next(it)
    print(result)
    result =next(it)
    print(result)
    result =next(it)
    print(result)
    result =next(it)
    print(result)
    #result =next(it)
    #print(result)
    
    #使用for循环遍历迭代器
    lis=[1,2,3,4]
    it=iter(lis)
    for i in it:
        print(i,end=' ')

    '''
    1.迭代器类似于有序序列,但无法知道迭代器的长度,只能通过next()得到下一个元素
    2.迭代器可以节省内存和空间

    '''
    #迭代器和可迭代的区别
    '''
    1.凡是可以作用于for循环的对象都是可以迭代的类型
    2.凡是可以作用于next()函数的对象都是迭代器类型
    3.list/dict/str等是可以迭代的但不是迭代器,无法使用next()函数无法调用,但可以通过iter()函数将它们转换成迭代器。

    '''

  • 相关阅读:
    进程与线程
    the art of seo(chapter seven)
    the art of seo(chapter six)
    the art of seo(chapter five)
    the art of seo(chapter four)
    the art of seo(chapter three)
    the art of seo(chapter two)
    the art of seo(chapter one)
    Sentinel Cluster流程分析
    Sentinel Core流程分析
  • 原文地址:https://www.cnblogs.com/w-yumiao/p/8324186.html
Copyright © 2011-2022 走看看