迭代器
1)可迭代对象包含迭代器。
2)如果一个对象拥有__iter__方法,其是可迭代对象;如果一个对象拥有next方法,其是迭代器。
3)定义可迭代对象,必须实现__iter__方法;定义迭代器,必须实现__iter__和next方法。
可迭代的对象,在python中内部含有 ’ _ _iter _ _’ 方法的对象就是可迭代对象,如:str、list、tuple、dict、set、range、等
获取对象所有的方法并且以字符串的形式表现:dir()
#获取一个对象的所有方法:dir()
s1 = "a,b,c,d,e,f,g"
l1 = [1,2,3,4,5,6]
print(dir(s1))
print(dir(l1))
# ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
# ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
**# 判断一个对象是否是可迭代对象如下:**
print('__iter__' in dir(s1))
#True
迭代器
判断一个对象是否是迭代器如下:
with open("文件1",encoding="utf-8",mode="w") as f1:
print(('__iter__' in dir(f1))and ('__next__' in dir(f1)))
# True
print(('__iter__' in dir(f1))and ('__next__' in dir(f1)))
#可迭代对象可以转换成迭代器
s1 = "abcdefg" # 可迭代对象
aa = iter(s1) #转换成迭代器
print(aa)#<str_iterator object at 0x00000220CB8BDD30>
print(next(aa)) #a # 迭代取值
print(next(aa)) #b
bb = s1.__iter__() #转换成迭代器
print(bb) # <str_iterator object at 0x000001348B06DD30>
print(bb.__next__()) # a # 迭代取值
print(bb.__next__()) # b
lst = {"周润发","周星驰","周杰伦","周大福","周大生"} #集合是无顺序的 下面拿取数据是随机的
it = lst.__iter__() #拿到这个列表的迭代器
print(it.__next__())
print(it.__next__())
print(it.__next__())
print(it.__next__())
print(it.__next__())
# 周大福
# 周星驰
# 周润发
# 周大生
# 周杰伦
print(it.__next__()) # StopIteration 因为无东西了停止跌代
#利用while循环模拟for循环对迭代对象进行取值
l1 = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]#可迭代对象
#首先将可迭代对象转换成迭代器
l2 = iter(l1)
while 1:
try:
print(next(l2))
except StopIteration: #忽略迭代循环完毕多次__next__()的报错
break