迭代器和生成器
1、迭代器
迭代器是訪問集合元素的一種方式。迭代器對象從集合的第一個元素開始訪問,直到所有的元素被訪問完結束。迭代器只能往前不會后退,不過這也沒什么,因為人們很少在迭代途中往后退。另外,迭代器的一大優點是不要求事先准備好整個迭代過程中所有的元素。迭代器僅僅在迭代到某個元素時才計算該元素,而在這之前或之后,元素可以不存在或者被銷毀。這個特點使得它特別適合用於遍歷一些巨大的或是無限的集合,比如幾個G的文件
特點:
- 訪問者不需要關心迭代器內部的結構,僅需通過next()方法不斷去取下一個內容
- 不能隨機訪問集合中的某個值 ,只能從頭到尾依次訪問
- 訪問到一半時不能往回退
- 便於循環比較大的數據集合,節省內存
- next()就相當於調用__next__(),for也是
iterable(可迭代)對象
支持每次返回自己所包含的一個成員的對象
對象實現了__iter__方法
(1)序列類型,如 str,list,tuple,set
(2)非序列類型,如 dict, file
(3)用戶自定義的一些包含了__iter__()或__getitem__()方法的類
for循環可用於任何可迭代對象
for循環開始時,會通過迭代協議傳遞給iter()內置函數,從而能夠從可迭代對象中獲得一個迭代器,返回的對象含有需要的next()方法
>>> a = iter([1,2,3,4,5]) >>> a <list_iterator object at 0x101402630> >>> a.__next__() 1 >>> a.__next__() 2 >>> a.__next__() 3 >>> a.__next__() 4 >>> a.__next__() 5 >>> a.__next__() Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
或者
>>> l1 = [1,2,3,4,5] >>> l2 = l1.__iter__() >>> type(l2) <class 'list_iterator'> >>> next(l2) 1 >>> next(l2) 2 >>> next(l2) 3 >>> next(l2) 4 >>> next(l2) 5 >>> next(l2) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
2、生成器
一個函數調用時返回一個迭代器,那這個函數就叫做生成器(generator);如果函數中包含yield語法,那這個函數就會變成生成器;能夠用next()調用或for循環使用
def func(): yield 1 yield 2 yield 3 yield 4
上述代碼中:func是函數稱為生成器,當執行此函數func()時會得到一個迭代器。
>>> temp = func() >>> temp.__next__() 1 >>> temp.__next__() 2 >>> temp.__next__() 3 >>> temp.__next__() 4 >>> temp.__next__() Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
一些例子:
#示例:使用yield函數生成器,能夠用next()調用或for循環使用 >>> def genNum(x): ....: y = 0 ....: while y <= x: ....: yield y ....: y += 1 ....: >>> g1 = genNum(5) >>> next(g1) 0 >>> for i in g1: ....: print i ....: 1 2 3 4 5 #示例:求1到10的平方,可以使用列表解析或者生成器,也可以是用yield >>> def genNum(n): ....: i = 1 ....: while i <= 10: ....: yield i ** 2 ....: i += 1 ....: >>> g1 = genNum(5) >>> for i in g1: ....: print i ....: 1 4 9 16 25 36 49 64 81 100
利用生成器自定義range
def nrange(num): temp = -1 while True: temp = temp + 1 if temp >= num: return else: yield temp
列表解析和生成器表達式:
列表解析
列表解析是python迭代機制的一種應用,它常用於實現創建新的列表,因此要放置於[]中
語法:
[expression for iter_var in iterable]
[expression for iter_var in iterable if condition_expression]
示例1: >>> l1 = [1,2,3,4,5] >>> l2 = [x ** 2 for x in l1] >>> print(l2) [1, 4, 9, 16, 25] 示例2: >>> l3 = [ x ** 2 for x in l1 if x >= 3 ] >>> print(l3) [9, 16, 25] 示例3: >>> l5 = [ (i ** 2)/2 for i in range(1,11) ] >>> print(l5) [0, 2, 4, 8, 12, 18, 24, 32, 40, 50] 示例4: >>> import os >>> help(os.listdir) >>> filelist1 = os.listdir('/var/log/') >>> s1 = 'hello.log' >>> s1.endswith('.log') >>> True >>> s2 = 'hello' >>> s2.endswith('.log') >>> False >>> help(str.endswith) >>> filelist2 = [ i for i in filelist1 if i.endswith('.log') ] >>> print(filelist2) ['yum.log', 'anaconda.yum.log', 'dracut.log', 'anaconda.ifcfg.log', 'anaconda.program.log', 'anaconda.log', 'anaconda.storage.log', 'boot.log'] >>> filelist3 = [ i for i in os.listdir('/var/log/') if i.endswith('.log') ] >>> print(filelist3) ['yum.log', 'anaconda.yum.log', 'dracut.log', 'anaconda.ifcfg.log', 'anaconda.program.log', 'anaconda.log', 'anaconda.storage.log', 'boot.log'] 示例5: >>> l1 = ['x','y','z'] >>> l2 = [1,2,3] >>> l3 = [ (i,j) for i in l1 for j in l2 ] >>> print(l3) [('x', 1), ('x', 2), ('x', 3), ('y', 1), ('y', 2), ('y', 3), ('z', 1), ('z', 2), ('z', 3)] 示例6: >>> l1 = ['x','y','z'] >>> l2 = [1,2,3] >>> l3 = [ (i,j) for i in l1 for j in l2 if j != 1 ] >>> print(l3) [('x', 2), ('x', 3), ('y', 2), ('y', 3), ('z', 2), ('z', 3)]
生成器表達式
生成器表達式並不真正創建數字列表,而是返回一個生成器對象,此對象在每次計算出一個條目后,把這個條目“產生”(yield)出來
生成器表達式使用了"惰性計算"或稱作"延遲求值"的機制
序列過長,並且每次只需要獲取一個元素時,應當考慮使用生成器表達式而不是列表解析
生成器表達式與python 2.4引入
語法:
(expr for iter_var in iterable)
(expr for iter_var in iterable if condition_expr)
示例1: >>> g1 = ( i**2 for i in range(1,11)) >>> next(g1) 1 >>> next(g1) 4 示例2: >>> for j in ( i**2 for i in range(1,11) ): print(j/2)