Python 叠代器
阿新 • • 發佈:2017-10-11
bre print for brush 使用 int exce keys ext
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
Python 叠代器