Python 3 iter函数用法简述

本文详细介绍了Python中iter函数的使用方法,特别是当该函数接受两个参数时的具体应用场景。通过一个计数器类的实例,展示了如何利用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

 

转载于:https://www.cnblogs.com/saolv/p/9352795.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值