• python 迭代器


    例子一

    # define a list
    my_list = [4, 7, 0, 3]
    
    # get an iterator using iter()
    my_iter = iter(my_list)
    
    ## iterate through it using next() 
    
    #prints 4
    print(next(my_iter))
    
    #prints 7
    print(next(my_iter))
    
    ## next(obj) is same as obj.__next__()
    
    #prints 0
    print(my_iter.__next__())
    
    #prints 3
    print(my_iter.__next__())
    
    ## This will raise error, no items left
    next(my_iter)

    例子二

    for element in iterable:
        # do something with element

    的实现为

    # create an iterator object from that iterable
    iter_obj = iter(iterable)
    
    # infinite loop
    while True:
        try:
            # get the next item
            element = next(iter_obj)
            # do something with element
        except StopIteration:
            # if StopIteration is raised, break from loop
            break

    例子三

    class PowTwo:
        """Class to implement an iterator
        of powers of two"""
    
        def __init__(self, max = 0):
            self.max = max
    
        def __iter__(self):
            self.n = 0
            return self
    
        def __next__(self):
            if self.n <= self.max:
                result = 2 ** self.n
                self.n += 1
                return result
            else:
                raise StopIteration

    for i in PowTwo(5):

        print(i)

     

    输出

    1
    2
    4
    8
    16
    32

    执行

    >>> a = PowTwo(4)
    >>> i = iter(a)
    >>> next(i)
    1
    >>> next(i)
    2
    >>> next(i)
    4
    >>> next(i)
    8
    >>> next(i)
    16
    >>> next(i)
    Traceback (most recent call last):
    ...
    StopIteration

    例子四

    返回所有奇数

    class InfIter:
        """Infinite iterator to return all
            odd numbers"""
    
        def __iter__(self):
            self.num = 1
            return self
    
        def __next__(self):
            num = self.num
            self.num += 2
            return num

    执行

    >>> a = iter(InfIter())
    >>> next(a)
    1
    >>> next(a)
    3
    >>> next(a)
    5
    >>> next(a)
    7

  • 相关阅读:
    android LinearLayout设置selector不起作用解决
    LinearLayout 垂直滚动条
    安卓如何限制横屏和竖屏
    Android特效 五种Toast详解
    打开MySQL数据库远程访问的权限
    android edittext不弹出软键盘
    高速掌握Lua 5.3 —— 扩展你的程序 (1)
    10分钟-jQuery过滤选择器
    2014年软件设计师考试后记
    Spring监管下的Hibernate配置文件
  • 原文地址:https://www.cnblogs.com/sea-stream/p/10178713.html
Copyright © 2020-2023  润新知