可迭代对象:可以重复取值,并且每一次的取值都是在上一次的结果之上而来的。凡是内部有_iter_()方法的都是可迭代对象。
迭代器对象:通过序列类型._iter_(),得到返回值就是迭代器对象。
迭代取值方式:
print(迭代器对象._next_())
for循环内部原理:
for item in 可迭代对象:
print item
#重复迭代,每一次迭代的结果都是基于上一次的结果而来的 #可迭代对象:str, list, tuple, set, dict, f文件 # str = 'hello world' # list = [1,2,3] # tuple = (4,5,6) # dict = {'name':'nick','age':18} # set = {7,8,9} # f = open('a.txt','r',encoding='utf-8') #str 示范 # str_iter = str.__iter__() #通过str._iter_()获取迭代器对象str_iter # print(str_iter.__next__()) #通过迭代器对象str_iter._next_()获取值 # print(str_iter.__next__()) # print(str_iter.__next__()) #因为上述做法都是重复,可写成循环 #循环版本 #str_iter = str.__iter__() # while True: # print(str_iter.__next__()) #虽然可以循环了,但是取完最后一个值后报错:StopIteration #解决办法 # str_iter = str.__iter__() # while True: # try: #通过关键字try一直尝试,捕获异常 # print(str_iter.__next__()) # except StopIteration: #直到遇到StopIteration # break #就停下来 #for循环版本 # for item in f: # print(item) #可迭代对象是迭代器对象吗? # str_iter = str.__iter__() # print((str_iter is str)) #False 结论:可迭代对象不一定是迭代器对象 # list_iter = list.__iter__() # print((list_iter is list)) #False 结论:可迭代对象不一定是迭代器对象 # tuple_iter = tuple.__iter__() # print((tuple_iter is tuple)) #False 结论:可迭代对象不一定是迭代器对象 # set_iter = set.__iter__() # print((set_iter is set)) #False 结论:可迭代对象不一定是迭代器对象 # dict_iter = dict.__iter__() # print((dict_iter is dict)) #False 结论:可迭代对象不一定是迭代器对象 # f_iter = f.__iter__() # print((f_iter is f)) #True 文件比较特殊,它既是可迭代对象,又可以是迭代器对象 #迭代器对象也是一个可迭代对象 # str_iter = str.__iter__() # print(