• 在我的函数大全文章中只是简单介绍了iter函数的用法,即将容器类型或者序列类型转为迭代器对象,下面是iter函数的官方详细解释,带例子

  • 英文原文

iter(object[, sentinel ])
Return an iterator object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, object must be a collection object which supports the iteration protocol (the __iter__() method), or it must support the sequence protocol (the __getitem__() method with integer arguments starting at 0). If it does not support either of those protocols, TypeError is raised. If the second argument, sentinel, is given, then object must be a callable object. The iterator created in this case will call object with no arguments for each call to its __next__() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned.
See also Iterator Types.
One useful application of the second form of iter() is to read lines of a file until a certain line is reached. 

Thefollowing example reads a file until the readline() method returns an empty string:

with open('mydata.txt') as fp:
    for line in iter(fp.readline, ''): 
        process_line(line)
  • 译文和理解
返回迭代器对象
            第一个参数的解释基于第二个参数。 
            当第二个参数不存在, 第一个参数必须是支持迭代协议的容器类型对象,例如字典等, 或者是支持序列协议的序列类型对象,例如列表等,如果都不支持则报错。
            当第二个参数存在, 即哨兵参数存在,则第一个参数必须是可调用对象,即函数等,以此种方式创建的迭代器对象将会调用object,可调用对象参数调用时不需要参数,如果可调用对象调用后返回值与哨兵对象值相同, 则结束调用

        官方例子1with open('mydata.txt') as fp:
            for line in iter(fp.readline, ''): 
                process_line(line)

        个人理解:for循环的每一次会调用 fp.readline 方法,将方法调用产生的值与哨兵参数比较,相同则结束迭代,否则将方法调用产生的值返回并绑定到line 变量
        官方例子2<多进程最后一个例子>:
        def worker(input, output):
            for func, args in iter(input.get, 'STOP'):
                result = calculate(func, args)
                output.put(result)
        函数中 input和output 均是任务队列,每次循环从input队列中取出任务,若取出的任务不是'STOP' 则执行取出的任务,否则停止



Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐