英文文档:

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. 当TFS/VSTS遇上Power BI

    引言 众所周知,要对TFS进行深入的图表分析,往往需要依赖于SQL Server Analysis Service和SQL Server Reporting Service.虽然随着TFS对敏捷项目的 ...

  2. tensorflow用dropout解决over fitting-【老鱼学tensorflow】

    在机器学习中可能会存在过拟合的问题,表现为在训练集上表现很好,但在测试集中表现不如训练集中的那么好. 图中黑色曲线是正常模型,绿色曲线就是overfitting模型.尽管绿色曲线很精确的区分了所有的训 ...

  3. Jmeter中基本操作

    Jmeter中基本操作包括 1:线程组 2:HTTP信息头管理器 3:HTTP请求默认值 4:HTTP请求 5:查看结果树 操作步骤如下: 1.创建一个线程组 通俗的讲一个线程组,,可以看做一个虚拟用 ...

  4. sqlserver 删除表结构

    sqlserver-----------删除表结构use IndividualTaxGOdeclare @sql varchar(8000)while (select count(*) from sy ...

  5. vue基础4-数据绑定

    1.v-bind 只能实现数据额单向绑定,从M到V,无法实现数据的双向绑定 改变页面输入框的值,打印数据并未改变. 2.v-model 可以实现数据的双向绑定,从M到V.V到M.  注意:v-mode ...

  6. 让java代码在Idea外面运行起来

    今天在写聊天程序,终于写到双方通信的时候,发现idea只能开一个客户端.虽说可以开多线程来实现多开,但是懒得改动代码,所以我就试试能不能把jar包导出来运行.首先我用maven自带的工具打了jar包, ...

  7. BZOJ3497 : Pa2009 Circular Game

    令先手为$A$,后手为$B$,将相邻同色棋子合并成块,首先特判一些情况: 如果所有格子都是满的,那么显然$A$必败. 否则如果所有块都只有一个棋子,那么显然平局. 枚举$A$的第一步操作,如果可以使得 ...

  8. LPC 语言基础

    LPC是一种基于C语言开发的编程语言 主要用于写MUD(多使用着迷宫)游戏 LPC是一种面向对象的语言,它有object的概念,但是没有class LPC有四中函数类型1> apply 只能被游 ...

  9. Unable to connect to Redis; nested exception is io.lettuce.core.RedisConnectionException: Unable to connect to ;XX.XX.XX.XX:6379] with root cause

    java.net.ConnectException: Connection refused: no further information at sun.nio.ch.SocketChannelImp ...

  10. 180815 Python自学成才001

    1.为什么学习Python? Python:脚本语言,易入门,可移植. Python适用范围:web开发.自动化测试工具编写. 适用岗位:运维开发(运维).自动化测试(软件测试).Python开发(软 ...