zoukankan      html  css  js  c++  java
  • Python 3 iter函数用法简述

    iter是将参数对象转化为迭代器的函数,当参数只有一个的时候很好理解,但是,当参数是两个的时候怎么用呢?

    Python官方文档对于这种形式的解释是:“ 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.”。

    这句话的意思是说:如果传递了第二个参数,则object必须是一个可调用的对象(如,函数)。此时,iter创建了一个迭代器对象,每次调用这个迭代器对象的__next__()方法时,都会调用object。

    如果__next__的返回值等于sentinel,则抛出StopIteration异常,否则返回下一个值。

    class counter:
    
        def __init__(self, _start, _end):
            self.start = _start
            self.end = _end
    
        def get_next(self):
            s = self.start
            if(self.start < self.end):
                self.start += 1
            else:
                raise StopIteration
    
            return s
    
    
    c = counter(1, 5)
    iterator = iter(c.get_next, 3)
    print(type(iterator))
    for i in iterator:
        print(i)

    执行结果:

    <class 'callable_iterator'>

    1

    2

  • 相关阅读:
    linux中编写同步文件的脚本
    SSH实现免密登录
    关于ISO 15765-2的解读
    设置Tera Term
    串口通信有极限速度
    三相永磁电机电流采样
    eclipse中F3快捷键无法跳转到定义的解决方法
    电脑和航模杂志和电子开发网站汇总
    MC9S08DZ60经典单片机
    STM32的SWD调试
  • 原文地址:https://www.cnblogs.com/saolv/p/9352795.html
Copyright © 2011-2022 走看看