Python 内建函数 - iter(object[, sentinel])

Python的iter()函数用于返回一个迭代器对象。如果没有第二个参数,对象必须支持迭代或序列协议。如果提供sentinel参数,object必须是可调用的,当返回值等于sentinel时引发StopIteration。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Manual

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. 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)

直译

返回一个迭代器对象。第一个参数的解释会根据第二个参数是否存在而出现不同,没有第二个参数时,object必须是一个支持迭代协议(__iter__()方法)的对象集,或者它必须支持序列协议(整数参数从0起始的__getitem__()方法)。如果它不支持这些协议的任意一种,将引发TypeError。如果给定第二个参数sentinel,那么object必须是一个可调用对象,在这种情况下创建的迭代器,对于它的每个__next__()方法的调用,将可以不带参数调用对象。如果返回值等于sentinel,则引发StopIteration,其他情况下可以将值返回。
iter()的第二个形式中最有用的应用是,读取一个文件的行直至到达既定行。下面例子展示了读取一个文件直到readline()方法返回一个空字符串:

with open('mydata.txt') as fp:
    for line in iter(fp.readline, ''):
        process_line(line)

实例

>>> a = [1, 2, 3, 4, 5]
>>> for i in iter(a):
    print(i)

1
2
3
4
5

>>> i_a = iter(a)
>>> i_a.__next__()
1
>>> i_a.__next__()
2
>>> i_a.__next__()
3
...

>>> d = {'Friday': 5, 'Wednesday': 4, 'Monday': 1, 'Sunday': 0, 'Tuesday': 2, 'Saturday': 6, 'Thursday': 3}
>>> d.__getitem__('Monday')
1
>>> i_d = iter(d)
>>> i_d.__next__()
'Friday'
>>> i_d.__next__()
'Wednesday'
...

>>> e = iter({'Friday': 5, 'Wednesday': 4, 'Monday': 1, 'Sunday': 0, 'Tuesday': 2, 'Saturday': 6, 'Thursday': 3})
>>> next(e)
'Saturday'
>>> next(e)
'Friday'
···

拓展阅读

__getitem__()
__next__()
next()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值