您的位置:首页 > 移动开发 > Objective-C

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

2017-03-17 14:55 483 查看
Manual

直译

实例

拓展阅读

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()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python