Python之iter

Python的迭代器iter:

iter函数返回一个迭代器对象。第一个参数的含义取决于第二个参数是否存在。如果没有第二个参数,参数o必须是collection对象或是支持sequence协议。否则会引起TypeError错误。如果存在第二个参数,该参数是哨兵,那么参数o必须是可调用对象。这种情况下,当每次调用next方法时,迭代器都会不调用o,直到遇见哨兵,触发StopIteration。

iter(o[, sentinel])
Return an iterator object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, o 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 o must be a callable object. The iterator created in this case will call o 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.

第二种方式下,一个比较有用的应用是,读取一个文件的内容,直到遇到特定的行。下面的例子读取文件直到遇到空字符串:
One useful application of the second form of iter() is to read lines of a file until a certain line is reached. The following 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)

该用法在Swift中也有体现,源码如下:

#返回一个函数
def _make_timeout_reader(self, file_like):
        def timeout_reader():
            with ChunkReadTimeout(self.client_timeout):
                return file_like.read(self.network_chunk_size)
        return timeout_reader
timeout_reader = self._make_timeout_reader(obj_input)
try:
    #这里面用了一个iter的方式来迭代IO数据,感觉很巧妙,见python API文档中关于iter的介绍
    #iter的第一个参数是一个可调用的对象或函数,第二个参数是哨兵
    #通过for循环,每次迭代调用可调用的对象或函数,直到遇到哨兵为止
    for chunk in iter(timeout_reader, ''):
        start_time = time.time()
        if start_time > upload_expiration:
            self.logger.increment('PUT.timeouts')
            return HTTPRequestTimeout(request=request)
        etag.update(chunk)
        upload_size = writer.write(chunk)
        elapsed_time += time.time() - start_time
except ChunkReadError:
    return HTTPClientDisconnect(request=request)
except ChunkReadTimeout:
    return HTTPRequestTimeout(request=request)

 
 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值