标签:元组 迭代 class 函数 pid bsp 异常 字符 cep
iter()函数和next()函数
使用iter(序列)函数可以获得一个迭代器,使用next(迭代器)函数可以获得迭代器中的下一条数据,例如;
l = [1,2,3] s = ‘hello world‘ t = (1,2,3,‘hello‘) it1 = iter(l) it2 = iter(s) it3 = iter(t) print(next(it1)) # 1 print(next(it2)) # h print(next(it3)) # 1
StopIteration 异常
当迭代器中没有数据时,会抛出一个StopIteration 异常,利用该异常判断迭代结束,例如:
l = [1,2,3] it = iter(l) while True: try: x = next(it) print(x) except StopIteration as si: # print(‘end‘) break # 1 2 3
迭代字符串、列表、元组和字典
l = [1,2,3] s = ‘hello world‘ t = (1,2,3,‘hello‘) it1 = iter(l) it2 = iter(s) it3 = iter(t) print(next(it1)) # 1 print(next(it2)) # h print(next(it3)) # 1 # 字典 d = {‘pid‘:‘123‘,‘name‘:‘tom‘,‘age‘:‘20‘} it = iter(d) # keys for k in it: v = d[k] print(k,v ,end=‘ ‘)
使用for/while循环迭代
l = [1,2,3] it = iter(l) for x in it: print(x) # 1 2 3 it = iter(l) while True: try: x = next(it) print(x) except StopIteration as si: break # 1 2 3
标签:元组 迭代 class 函数 pid bsp 异常 字符 cep
原文地址:http://www.cnblogs.com/lcgsmile/p/7652048.html