首页 技术 正文
技术 2022年11月16日
0 收藏 463 点赞 3,424 浏览 1076 个字

Python 3中关于iter(object[, sentinel)]方法有两个参数。

使用iter(object)这种形式比较常见。

iter(object, sentinel)这种形式一般较少使用,Python的文档说明貌似也不容易理解。

故,在此举例说明一下此函数的用法。

1,iter(object)

Python官方文档对于这种形式的解释很容易理解。

此时,object必须是集合对象,且支持迭代协议(iteration protocol)或者支持序列协议(sequence protocol)。

说白了,也就是实现了__iter__()方法或者__getitem__()方法。

 lst = [1, 2, 3]
for i in iter(lst):
print(i)

执行结果:

1
2
3

2,iter(object, sentinel)

Python官方文档对于这种形式的解释是:“ 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.”。

这句话的意思是说:如果传递了第二个参数,则object必须是一个可调用的对象(如,函数)。此时,iter创建了一个迭代器对象,每次调用这个迭代器对象的__next__()方法时,都会调用object。

如果__next__的返回值等于sentinel,则抛出StopIteration异常,否则返回下一个值。

 class counter:     def __init__(self, _start, _end):
self.start = _start
self.end = _end def get_next(self):
s = self.start
if(self.start < self.end):
self.start += 1
else:
raise StopIteration return s c = counter(1, 5)
iterator = iter(c.get_next, 3)
print(type(iterator))
for i in iterator:
print(i)

执行结果:

<class ‘callable_iterator’>
1
2

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,000
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,512
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,358
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,141
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,771
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,849