迭代ssh
基本含義函數
迭代是重複反饋過程的活動,其目的一般是爲了接近併到達所需的目標或結果。每一次對過程的重複被稱爲一次「迭代」,而每一次迭代獲得的結果會被用來做爲下一次迭代的初始值。大數據
在計算科學中,迭代是程序中對一組指令(或必定步驟)的重複。它既能夠被用做通用的術語(與「重複」同義),也能夠用來描述一種特定形式的具備可變狀態的重複。ui
操做spa
1 >>> lst =[1,2,3,4] 2 >>> for i in lst: #for 循環讀取列表中的每個元素 3 ... print i 4 ... 5 1 6 2 7 3 8 4 9 >>> lit =iter(lst) #建立迭代器對象 10 >>> type(lit) #列表迭代器 11 <type 'listiterator'> 12 >>> dir(lit) #查看列表迭代器的方法 ,next() 13 ['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__length_hint__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'next'] 14 >>> lit.next() 列表元素中的第一個元素 15 1 16 >>> lit.next() 列表元素中的第二個元素 17 2 18 >>> lit.next() 19 3 20 >>> lit.next() 21 4 22 >>> lit.next() 23 Traceback (most recent call last): 24 File "<stdin>", line 1, in <module> 25 StopIteration 26 >>> lit =iter(lst)
#這個for循環與前面list for循環,從結果看是同樣的。實際上,運行過程上是有區別的。
相似文件,讀取大數據的時候,用for循環完成對迭代器對象中每一個元素讀取的過程,可體現出迭代器的優點。
由於是把所要讀取的元素一個一個拿到內存,而不是一下所有放到內存
27 >>> for i in lit: 28 ... print i 29 ... 30 1 31 2 32 3 33 4 34 >>> help(iter) 35 Help on built-in function iter in module __builtin__: 36 #返回值是一個迭代對象
#參數必須是符合迭代協議的對象,或者是序列對象 37 iter(...) 38 iter(collection) -> iterator 39 iter(callable, sentinel) -> iterator 40 41 Get an iterator from an object. In the first form, the argument must 42 supply its own iterator, or be a sequence. 43 In the second form, the callable is called until it returns the sentinel. 44 45 >>>
迭代是Python最強大的功能之一,是訪問集合元素的一種方式。code
迭代器是一個能夠記住遍歷的位置的對象。orm
迭代器對象從集合的第一個元素開始訪問,直到全部的元素被訪問完結束。迭代器只能往前不會後退。對象
迭代器有兩個基本的方法:iter() 和 next()。blog
字符串,列表或元組對象均可用於建立迭代器內存
迭代器對象能夠使用常規for語句進行遍歷
也能夠使用 next() 函數