前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >详解Python内置函数iter()用法

详解Python内置函数iter()用法

作者头像
Python小屋屋主
发布2018-04-16 14:45:43
3.5K0
发布2018-04-16 14:45:43
举报
文章被收录于专栏:Python小屋Python小屋Python小屋

iter()函数用来返回指定对象的迭代器,有两种用法:iter(iterable)和iter(callable, sentinel),前者要求参数必须为序列或者有自己的迭代器,后者会持续调用参数callable直至其返回sentinel。

>>> x = [1, 2, 3]

>>> next(x)

TypeError: 'list' object is not an iterator

>>> y = iter(x) #根据列表创建迭代器

>>> next(y)

1

>>> next(y)

2

>>> x = {1, 2, 3}

>>> y = iter(x) #根据字典创建迭代器

>>> next(y)

1

>>> class T:

def __init__(self, seq):

self.__data = list(seq)

def __iter__(self): #特殊方法,对应于内置函数iter()

return iter(self.__data)

>>> t = T(range(3))

>>> next(t) #对象t不可迭代

TypeError: 'T' object is not an iterator

>>> ti = iter(t) #根据t创建迭代器

>>> next(ti)

0

>>> next(ti)

1

>>> from queue import Queue

>>> q = Queue() #创建队列对象

>>> for i in range(5):

q.put(i) #依次放入5个数字

>>> q.put('END') #放入结束标志

>>> def test():

return q.get()

>>> for item in iter(test, 'END'): #持续执行test()函数,直到返回’END’

print(item, end=' ')

0 1 2 3 4

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2016-11-08,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Python小屋 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档