您的位置:首页 > 编程语言 > Python开发

Python学习21:迭代器的使用

2014-07-29 10:06 741 查看
迭代器为类序列对象提供一个类序列的接口。

是一组数据结构。

迭代器是一个有next()方法的对象,不是通过索引来技术。

for i in ls: :就是才通用的next()的方法获得元素。所有的元素都取出之后,会引发StopIteration异常(不是错误,是告诉外部调用者,迭代结束)

不能复制一个迭代器

reversed():返回一个反向访问的迭代器。

enumerate():内建函数返回迭代器

使用迭代器:

#FileName: ite.py

#序列使用迭代器---------------------------
#定义元组
myTuple = ('Hello','Python','World')
ls = ['Python','Windows','Mirc']

#创建迭代器
it = iter(myTuple)

#使用__next__返回下一项
print(it.__next__(),end = ' ')  #python2使用next()
print(it.__next__(),end = ' ')
print(it.__next__(),end = ' ')
# print(it.__next__(),end = ' ')  #抛出StopIteration异常

print('\n')
#使用for循环迭代序列
for i in myTuple:
print(i,end = ' ')
print('\n')

print("---------------------")
#以上for循环相当于一下
#创建迭代器
it2 = iter(myTuple)

while True:
try:
print(it2.__next__(),end = ' ')
except StopIteration :
break
print('\n')

#字典使用迭代器------------------------------
print('字典使用迭代器---------------------')
#定义字典
dic = dict(name = 'jiezhj',blog = 'http://csdn.com/jiezhj',date = '2014年7月29日')
#字典迭代器会遍历字典的keys
# for key in dic.keys()  等同于for key in dic

#使用for循环迭代器
for key in dic:
print(dic[key],end = ' ')
print()

it3 = iter(dic)
#代印出来的是字典的key
print(it3.__next__(),end = ' ')
print(it3.__next__(),end = ' ')
print(it3.__next__(),end = ' ')

#文件使用迭代器------------------------------
#文件对象生成的迭代器自动调用readline方法

fp = open('ite.py','rb')
for line in fp:
pass
fp.close()


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: