next():
next()返回迭代器的下一個項目
next語法:
next(iterator[,dafault])
iterator -- 可迭代對象
default -- 可選,用於設置在沒有下一個元素時返回該默認值,如果不設置,又沒有下一個元素則會觸發 StopIteration 異常。
e.g.:
1 #!/usr/bin/python 2 # -*- coding: UTF-8 -*- 3 4 # 首先獲得Iterator對象: 5 it = iter([1, 2, 3, 4, 5]) 6 # 循環: 7 while True: 8 try: 9 # 獲得下一個值: 10 x = next(it) 11 print(x) 12 except StopIteration: 13 # 遇到StopIteration就退出循環 14 break
iter():
iter()函數用來生成迭代器
iter語法:
iter(object[, sentinel])
object -- 支持迭代的集合對象。
sentinel -- 如果傳遞了第二個參數,則參數 object 必須是一個可調用的對象(如,函數),此時,iter 創建了一個迭代器對象,每次調用這個迭代器對象的__next__()方法時,都會調用 object。
e.g.:
>>>lst = [1,2,3] >>>for i in iter(lst): print(i) ... ... 1 2 3
