首页 > 后端开发 > Python教程 > Python内置函 iter

Python内置函 iter

高洛峰
发布: 2016-11-04 14:52:38
原创
1361 人浏览过

英文文档:

iter(object[, sentinel])

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.

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)

 说明:

  1. 函数功能返回一个可迭代对象。

  2. 当第二个参数不提供时,第一个参数必须是一个支持可迭代协议(即实现了__iter__()方法)的集合(字典、集合、不可变集合),或者支持序列协议(即实现了__getitem__()方法,方法接收一个从0开始的整数参数)的序列(元组、列表、字符串),否则将报错。

>>> a = iter({'A':1,'B':2}) #字典集合
>>> a
<dict_keyiterator object at 0x03FB8A50>
>>> next(a)
&#39;A&#39;
>>> next(a)
&#39;B&#39;
>>> next(a)
Traceback (most recent call last):
  File "<pyshell#36>", line 1, in <module>
    next(a)
StopIteration
 
>>> a = iter(&#39;abcd&#39;) #字符串序列
>>> a
<str_iterator object at 0x03FB4FB0>
>>> next(a)
&#39;a&#39;
>>> next(a)
&#39;b&#39;
>>> next(a)
&#39;c&#39;
>>> next(a)
&#39;d&#39;
>>> next(a)
Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    next(a)
StopIteration
登录后复制

3. 当第二个参数sentinel提供时,第一个参数必须是一个可被调用对象。创建的迭代对象,在调用__next__方法的时候会调用这个可被调用对象,当返回值和sentinel值相等时,将抛出StopIteration异常, 终止迭代。

# 定义类
>>> class IterTest: 
    def __init__(self):
        self.start = 0
        self.end = 10
    def get_next_value(self):
        current = self.start
        if current < self.end:
            self.start += 1
        else:
            raise StopIteration
        return current

>>> iterTest = IterTest() #实例化类
>>> a = iter(iterTest.get_next_value,4) # iterTest.get_next_value为可调用对象,sentinel值为4
>>> a
<callable_iterator object at 0x03078D30>
>>> next(a)
>>> next(a)
>>> next(a)
>>> next(a)
>>> next(a) #迭代到4终止
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    next(a)
StopIteration
登录后复制


相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板