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

    #迭代器

    迭代的工具,迭代是更新换代,也可以说成重复,可以基于上一次的结果推出下一次的结果

    可迭代对象

    python中一切皆对象,对这一切的对象中 但凡有__iter__方法的对象,都是可迭代对象。

    x = 1  # 不可迭代对象
    
    s = 'nick'  # 可迭代对象
    s.__iter__()
    lt = [1, 2, 3]  # 可迭代对象
    dic = {'a': 1, 'b': 2}  # 可迭代对象
    tup = (1,)  # 元组只有一个元素必须得加逗号# 可迭代对象
    set = {1, 2, 3}  # 可迭代对象
    f = open('time.py')  # 可迭代对象
    
    
    def func():  # 不可迭代对象
        pass
    

    Python内置str、list、tuple、dict、set、file都是可迭代对象.然后出了数字类型和函数之外都是可迭代对象

    迭代器对象

    具有__iter__以及__next__方法的叫做迭代器对象

    s = 'nick'  # 可迭代对象,不属于迭代器对象
    s.__iter__()
    lt = [1, 2, 3]  # 可迭代对象,不属于迭代器对象
    dic = {'a': 1, 'b': 2}  # 可迭代对象,不属于迭代器对象
    tup = (1,)  # 元组只有一个元素必须得加逗号# 可迭代对象,不属于迭代器对象
    se = {1, 2, 3}  # 可迭代对象,不属于迭代器对象
    f = open('time.py')  # 可迭代对象,迭代器对象
    
    

    只有文件是迭代器对象

    # 不依赖索引的数据类型迭代取值
    dic = {'a': 1, 'b': 2, 'c': 3}
    iter_dic = dic.__iter__()
    print(iter_dic.__next__())
    print(iter_dic.__next__())
    print(iter_dic.__next__())
    # print(iter_dic.__next__())  # StopIteration:
    

    a

    b

    c

    # 依赖索引的数据类型迭代取值
    lis = [1, 2, 3]
    iter_lis = lis.__iter__()
    print(iter_lis.__next__())
    print(iter_lis.__next__())
    print(iter_lis.__next__())
    # print(iter_lis.__next__())  # StopIteration:
    1
    

    1

    2

    3

    上面方法十分繁琐,我们可以使用while循环精简下。其中使用的try...except...为异常处理模块.

    s = 'hello'
    iter_s = s.__iter__()
    
    while True:
        try:
            print(iter_s.__next__())
        except StopIteration:
            break
    

    h
    e
    l
    l
    o

    总结

    可迭代对象: 具有__iter__方法的对象就是可迭代对象,除了数字类型和函数都是可迭代对象

    迭代器对象: 具有__iter____next__方法的都是迭代器对象,只有文件

    迭代器对象一定是可迭代对象; 可迭代对象不一定是迭代器对象

    for循环原理

    for循环==迭代器循环

    dic ={'a':1,'b':2}
    for i in dic:
        print(i)
    
    # 1. 把lt(可迭代对象/迭代器对象)用__iter__方法转换成迭代器对象
    # 2. 使用__next__取出迭代器里的所有值
    # 3. 使用__next__方法取尽迭代器中的所有值,一定会报错,通过异常捕捉退出while循环
    
    # 解决了不依赖索引取值
    
    
    # dic ={'a':1,'b':2}
    # dic_iter = iter(dic)
    # print(next(dic_iter))
    # print(next(dic_iter))
    
  • 相关阅读:
    UVa 1451 Average (斜率优化)
    POJ 1160 Post Office (四边形不等式优化DP)
    HDU 3507 Print Article (斜率DP)
    LightOJ 1427 Substring Frequency (II) (AC自动机)
    UVa 10245 The Closest Pair Problem (分治)
    POJ 1741 Tree (树分治)
    HDU 3487 Play with Chain (Splay)
    POJ 2828 Buy Tickets (线段树)
    HDU 3723 Delta Wave (高精度+calelan数)
    UVa 1625 Color Length (DP)
  • 原文地址:https://www.cnblogs.com/aden668/p/11340697.html
Copyright © 2011-2022 走看看