zoukankan      html  css  js  c++  java
  • Python开发基础 day7 迭代器

    迭代器

     迭代:

     1 重复
     2 下一次重复是基于上一次的结果


    # while True:
    # cmd=input('>>: ')
    # print(cmd)

    # l=['a','b','c','d']
    # count=0
    # while count < len(l):
    # print(l[count])
    # count+=1

    #
    # l=['a','b','c','d']
    # for count in range(len(l)):
    # print(l[count])


    # d={'a':1,'b':2,'c':3}
    #
    # for k in d:
    # print(k)

    '''
    python为了提供一种不依赖于索引的迭代方式,
    python会为一些对象内置__iter__方法
    obj.__iter__称为可迭代的对象
    '''
    # s1='hello'
    # l=[1,2,3]
    # t=(1,2,3)
    # set1={1,2,3}
    # d={'a':1,'b':2,'c':3}
    #
    # f=open('db.txt',encoding='utf-8')


    obj.__iter__() 得到的结果就是迭代器

    得到的迭代器:既有__iter__又有一个__next__方法
    # d={'a':1,'b':2,'c':3}
    #
    # i=d.__iter__() #i叫迭代器
    # print(i)
    # print(i.__next__())
    # print(i.__next__())
    # print(i.__next__())
    # print(i.__next__()) #StopIteration


    l=['x','y','z']
    # print(l[2])
    # print(l[0])

    # i=l.__iter__()
    # print(i.__next__())
    # print(i.__next__())
    # print(i.__next__())


    迭代器的优点
    1:提供了一种不依赖于索引的取值方式
    2:惰性计算。节省内存

    迭代器的缺点:
    1:取值不如按照索引取值方便
    2:一次性的。只能往后走不能往前退
    3:无法获取长度

     

    #
    # for item in l: #i=l.__iter__()
    # print(item)


    for item in 1:
    print(item)
    迭代器

  • 相关阅读:
    学习日报
    阅读笔记2
    学习日报
    记账本开发7
    记账本开发6
    学习日报
    记账本开发5
    今日总结
    今日总结
    家庭记账本7
  • 原文地址:https://www.cnblogs.com/bsxq/p/7018011.html
Copyright © 2011-2022 走看看