英文文档:

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. mysql驱动问题

    Unknown initial character set index '255' received from server. Initial client character 解决方法 驱动版本不对 ...

  2. notes for lxf(三)

    纯函数式编程是没有变量的,只要输入确定输出就确定 指高度抽象的编程范式 特点 函数本身可以作为参数传入 或者允许返回一个函数 Higher-order function 一个函数可以接收另一个函数作为 ...

  3. DCDC设计指南二

    DCDC电源设计指导:二 这一讲以一款SOP-8封装的Synchronous Step-Down Converter(同步降压转换器)电源IC为例,讲下电源的PCB设计. 如第一讲中所说,开始设计时就 ...

  4. Exp5 MSF基础应用 20164302 王一帆

    1.实验内容 1.1实验要求 一个主动攻击实践,ms08_067; 一个针对浏览器的攻击,MS10-018(成功且唯一),MS12-004(成功且唯一): 一个针对客户端的攻击,adobe_toolb ...

  5. 可视化利器Visdom

    可视化利器Visdom 最近在使用Pytorch炼丹,单纯地看命令行输出已经无法满足调试的需求,尝试了facebook开源的visdom,感觉非常优雅,支持numpy和torch 安装 $ pip i ...

  6. 我们来谈谈最近最热门的微信小程序

    最近微信小程序真是火到不行,我们的经理大人也就此给我做了一定的培训.他讲的太好,我实在忍不住跟大家简单分享一下: 1.什么是微信小程序? 一种不需要下载安装即可使用的应用,它实现了应用“触手可及”的梦 ...

  7. 关于docker jenkins启动时失败的问题处理

    最近在做持续集成,然后使用docker 运行jenkins docker run -d  -p 8088:8080 -p 50000:50000 -v /home/docker/jenkins_hom ...

  8. 微信公众平台测试号 “微信登录失败,redirect_uri域名与后台配置不一致,错误代码10003”

    设置"网页授权获取用户基本信息" 点击"修改" 弹出"OAuth2.0网页授权",注意域名不加"https://"或&q ...

  9. Jquery weui picker 支持label和value

    万年没更新了. 最近用jquery weui. 在使用picker时需要一些问题. 就是让picker 显示label, 但是取值的时候取value用于存储. 官网例子如下 Jquery-weui 官 ...

  10. .NET题目(收集来自网络)

    1: .NET和c#有什么区别? 答: .NET一般是指.NET FrameWork框架,是一种平台,一种技术 c#是一种编程语言,是可以基于.NET平台的应用 2: c#中的委托是什么?事件是不是一 ...