英文文档:

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)
'A'
>>> next(a)
'B'
>>> next(a)
Traceback (most recent call last):
File "<pyshell#36>", line 1, in <module>
next(a)
StopIteration >>> a = iter('abcd') #字符串序列
>>> a
<str_iterator object at 0x03FB4FB0>
>>> next(a)
'a'
>>> next(a)
'b'
>>> next(a)
'c'
>>> next(a)
'd'
>>> 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)
0
>>> next(a)
1
>>> next(a)
2
>>> next(a)
3
>>> next(a) #迭代到4终止
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
next(a)
StopIteration

Python内置函数(36)——iter的更多相关文章

  1. Python内置函数(28)——iter

    英文文档: iter(object[, sentinel]) Return an iterator object. The first argument is interpreted very dif ...

  2. Python内置函数(36)——reversed

    英文文档: reversed(seq) Return a reverse iterator. seq must be an object which has a __reversed__() meth ...

  3. Python内置函数(4)

    Python内置函数(4) 1.copyright 交互式提示对象打印许可文本,一个列表贡献者和版权声明 2.credits 交互式提示对象打印许可文本,一个贡献者和版权声明的列表 3.delattr ...

  4. Python内置函数和内置常量

    Python内置函数 1.abs(x) 返回一个数的绝对值.实参可以是整数或浮点数.如果实参是一个复数,返回它的模. 2.all(iterable) 如果 iterable 的所有元素为真(或迭代器为 ...

  5. Python | 内置函数(BIF)

    Python内置函数 | V3.9.1 | 共计155个 还没学完, 还没记录完, 不知道自己能不能坚持记录下去 1.ArithmeticError 2.AssertionError 3.Attrib ...

  6. Python 内置函数笔记

    其中有几个方法没怎么用过, 所以没整理到 Python内置函数 abs(a) 返回a的绝对值.该参数可以是整数或浮点数.如果参数是一个复数,则返回其大小 all(a) 如果元组.列表里面的所有元素都非 ...

  7. 【转】python 内置函数总结(大部分)

    [转]python 内置函数总结(大部分) python 内置函数大讲堂 python全栈开发,内置函数 1. 内置函数 python的内置函数截止到python版本3.6.2,现在python一共为 ...

  8. python内置函数,匿名函数

    一.匿名函数 匿名函数:为了解决那些功能很简单的需求而设计的一句话函数 def calc(n): return n**n print(calc(10)) #换成匿名函数 calc = lambda n ...

  9. python 内置函数总结(大部分)

    python 内置函数大讲堂 python全栈开发,内置函数 1. 内置函数 python的内置函数截止到python版本3.6.2,现在python一共为我们提供了68个内置函数.它们就是pytho ...

随机推荐

  1. 一起学爬虫——如何爬取通过ajax加载数据的网站

    目前很多网站都使用ajax技术动态加载数据,和常规的网站不一样,数据时动态加载的,如果我们使用常规的方法爬取网页,得到的只是一堆html代码,没有任何的数据. 请看下面的代码: url = 'http ...

  2. matplotlib函数理解

    cumsum(),通常用于计算一个数组各行的累加值,函数用法是B = cumsum(A,dim),或B = cumsum(A). def cumsum(self, axis=0, *args, **k ...

  3. DOS批处理中对含有特殊字符的文件名的处理方法

    从一些网站下载的文件,文件名带有广告,典型的就是网站的名称和域名,搞得文件名很长.在一些场景下,广告看得见,真正的文件名却被...了.在以前,我是遇到就手工去掉广告,但一是麻烦,二是效率低.反正经常下 ...

  4. Mac下brew安装JDK的教程

    ---恢复内容开始--- 安装命令: brew cask install java 默认应该会下载jdk7 也可以指定下载版本brew cask install java6 注意: brew inst ...

  5. IDEA+Tomcat+Maven+SpringMVC基于Java注解配置web工程

    1.在IDEA中新建Maven工程,使用archetype. 2.添加Maven依赖 <dependencies> <dependency> <groupId>ju ...

  6. web 10

    一.Iterations : 1.do...while : 创建执行指定语句的循环,直到测试条件评估为false.在执行语句后评估条件,导致指定语句至少执行一次. 例子:在以下示例中,do...而循环 ...

  7. R语言grid包just参数如何just图形位置

    思路   grid的画图函数都含有just,但是just参数的是怎么调节图形位置的总是让人非常费解,于是便写了代码来一探究竟.   思路非常简单:放一个2*2的布局viewport,每个布局里面放一个 ...

  8. Android Studio 去除上方标题

    选中代码再Ctrl+shift+'/' 可加/***/注释 https://blog.csdn.net/wuqingsen1/article/details/78554117 styles.xml & ...

  9. 小程序textarea完美填坑

    相信做微信小程序的码友们都被textarea这个原生组件坑过,什么placeholder位置错乱,穿透弹窗或遮罩层,ios上输入法弹起后换行输入内容遮挡,删除输入内容时内容被遮挡等等... 反正综上所 ...

  10. ASP.NET Core Web App应用第三方Bootstrap模板

    引言 作为后端开发来说,前端表示玩不转,我们一般会选择套用一些开源的Bootstrap 模板主题来进行前端设计.那如何套用呢?今天就简单创建一个ASP.NET Core Web MVC 模板项目为例, ...