迭代器
迭代器协议:
满足两个条件: 1. 有 iter 方法; 2. 有 next 方法
- # -*-coding:utf-8 -*-
- __date__ = 2018/3/18
- __author__ = xiaojiaxin
__file_name__ = 迭代器
- # 生成器都是迭代器, 迭代器不一定是生成器
- l=[1,2,3,4]
- d=iter(l)
- print(d)
- # <list_iterator object at 0x000000CB6FC4B1D0>
- print(next(d))
- for i in d:
- print(i)
for 循环内部三件事:
1. 调用可迭代对象的 iter 方法, 返回一个迭代器对象;
2. 调用迭代器的 next 方法
3. 处理 StopIteration 方法
- for i in [1,2,3,4]:
- print(i)
- # [1,2,3,4] 本身没有 next 方法, 是 for 循环给他做的
- from collections import Iterator
- from collections import Iterable
- print(isinstance([1,2,3,4],list)) #判断是否为指定数据类型
- # True
- print(isinstance(1,list))
- # False
- print(isinstance([1,2],Iterable))
- # True
- print(isinstance([1,2],Iterator))
- # False
- # [1,2] 是可迭代对象, 但是不是迭代器
在 for 循环里也把文件转换成了迭代器
- max1=0
- record=0
- count=1
- with open("hello.txt","r",encoding="utf-8") as f:
- for i in f:
- if len(i.strip())>max1:
- max1=len(i)
- record=i
- count+=1
- print("the longest sentence is %s,it is the %d line,It has %d words"%(record,count,max1))
大家对内容有任何问题, 欢迎留言, 一定在第一时间解答, 谢谢大家!
来源: http://www.bubuko.com/infodetail-2544999.html