• 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

  • 相关阅读:
    docker-compose常用命令-详解
    Docker的4种网络模式
    docker-compose常用命令-详解
    windows 10安装nodejs(npm,cnpm),在谷歌浏览器上安装vue开发者工具 vue Devtools
    @Pointcut注解
    leetcode做题总结
    win10右键添加在此处打开powershell
    怎样从 bat 批处理文件调用 PowerShell 脚本
    Android Google Play app signing 最终完美解决方式
    526. Beautiful Arrangement
  • 原文地址:https://www.cnblogs.com/sea-stream/p/10178713.html
Copyright © 2020-2023  润新知