英文文档:

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 sentinelStopIteration 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内置函数(28)——iter的更多相关文章

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

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

  2. Python内置函数(28)——hash

    英文文档: hash(object)Return the hash value of the object (if it has one). Hash values are integers. The ...

  3. python内置函数简单归纳

    做python小项目的时候发现熟练运用python内置函数,可以节省很多的时间,在这里整理一下,便于以后学习或者工作的时候查看.函数的参数可以在pycharm中ctrl+p查看. 1.abs(x):返 ...

  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内置函数,匿名函数

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

  8. Python之路(第八篇)Python内置函数、zip()、max()、min()

    一.python内置函数 abs() 求绝对值 例子 print(abs(-2)) all() 把序列中每一个元素做布尔运算,如果全部都是true,就返回true, 但是如果是空字符串.空列表也返回t ...

  9. python内置函数大全(分类)

    python内置函数大全 python内建函数 最近一直在看python的document,打算在基础方面重点看一下python的keyword.Build-in Function.Build-in ...

随机推荐

  1. 作为一个懒虫,如何优雅的使用windows

    懒虫windows系列(一) 首先是快捷键,因为自己太懒了,觉得用鼠标很麻烦,下面总结一下自己最常用的快捷键(windows10 ) Ctrl+Shift+N:新建文件夹 F2:重命名 Ctrl + ...

  2. Problem : 1196 ( Lowest Bit )

    第一次一次通过,逻辑太简单... #include<iostream> using namespace std; void main() { int n; while(cin>> ...

  3. 记一次 synchronized 锁字符串引发的坑兼再谈 Java 字符串

    业务有一个需求,我把问题描述一下: 通过代理IP访问国外某网站N,每个IP对应一个固定的网站N的COOKIE,COOKIE有失效时间. 并发下,取IP是有一定策略的,取到IP之后拿IP对应的COOKI ...

  4. [C#].Net Core下全局自定义身份过滤器使用AllowAnonymous属性

    假设一种情况:项目中需要做认证和权限控制,而且需要权限才能访问的控制器要远多于可以匿名访问的(类似AO系统那样,登陆了才能用). 那在每个控制器上加一个 [Authorize] 是能解决问题,反正正我 ...

  5. kubernetes实现用户自定义扩缩容

    本文章主要参考walkthrough,aggregation和auth.涉及custom metric API的注册认证以及API server aggregation的相关知识.walkthroug ...

  6. 使用mescroll来实现移动端页面上拉刷新, 下拉加载更多功能

    * mescroll请参考官方文档 1. 使用mescroll实现下拉滑动的效果: (仅仅效果, 有的页面不需要刷新数据, 只要你能下拉就行) 代码如下: var mescroll = new MeS ...

  7. JAVA 新手注意事项

    1.  System.exit(0);  强行关闭虚拟机         2.   System.out.println("*")     输出一个*并换行    (没后面的ln表 ...

  8. Java基础_Java概述

    Java_概述 特点: 平台的移植性 开源 面向对象 多线程 安全性 工作方式: 先编译再解释执行. 先通过Javac命令将Java源代码编译成字节码文件(bytecode,类文件,.class,中间 ...

  9. npm 和bower之间的区别

    (一) npm是node js的包管理器,用来下载安装node js的第三方工具包,也可以用来发布你自己开发的工具包.通过npm可以安装bower,命令如下: npm install -g bower ...

  10. js前端读写文件的方法(json、excel)

    1.前端读取文件的实现 关键:利用文件上传对话框预览本地文件.利用FileReader读取文件 前端预览本地文件 <input tabindex="-1" id=" ...