''' 1、迭代器协议:1,对象必须提供一个next()方法 2,执行该方法,要么返回迭代中的下一项,要么引发一个StopIteration异常,以终止跌倒 2、可迭代对象, 实现了迭代器协议的对象 3、for循环的本质就是遵循迭代器协议去访问对象 4、字符串,列表,元组,字典,集合,文件这些均不限属于可迭代对象, for循环之因此能遵循迭代器协议对其进行访问,其实是调用了这些对象内的iter()方法,将这些对象变成了可迭代对象 再经过next()方法·取值,直到取到stopiteration异常时终止迭代,中止循环 ''' # vocaloid_list=['miku','rin','ran','ruka'] # vocaloid=vocaloid_list.__iter__() # print(vocaloid.__next__()) #输出结果:miku # print(vocaloid.__next__()) #输出结果:rin # print(vocaloid.__next__()) #输出结果:ran # print(vocaloid.__next__()) #输出结果:ruka # print(vocaloid.__next__()) #报告StopIteration异常 ''' 内置函数中的next()函数与__next__()方法的效果是同样的 next(变量) 《--------》变量.__next__() ''' # vocaloid_list=['miku','rin','ran','ruka'] # vocaloid=vocaloid_list.__iter__() # print(vocaloid.__next__()) #输出结果:miku # print(next(vocaloid)) #输出结果:rin # print(vocaloid.__next__()) #输出结果:ran # print(vocaloid.__next__()) #输出结果:ruka # print(vocaloid.__next__()) #报告StopIteration异常 ''' 对于有序序列:字符串,列表,元组等虽然能够使用while如下标的方式遍历, 但对于无序的字典集合文件等对象则没法遍历 for循环经过基于迭代器协议访问对象,提供了一个统一的遍历全部对象的方法 ''' ''' 经过while模拟for循环的工做方式= ''' def iteration_while(x): temp=x.__iter__() while True: # result=temp.__next__() # if result == 'StopIteration': # print('监测到StopIteration异常,终止循环') # # break # else: # print(result) try: print(temp.__next__()) except StopIteration: print('监测到StopIteration异常,迭代结束') break vocaloid_list = ['miku', 'rin', 'ran', 'ruka'] iteration_while(vocaloid_list)