Python自動化運維之七、生成器、迭代器、列表解析、迭代器表達式

迭代器和生成器

一、迭代器

迭代器是訪問集合元素的一種方式。迭代器對象從集合的第一個元素開始訪問,直到全部的元素被訪問完結束。迭代器只能往前不會後退,不過這也沒什麼,由於人們不多在迭代途中日後退。另外,迭代器的一大優勢是不要求事先準備好整個迭代過程當中全部的元素。迭代器僅僅在迭代到某個元素時才計算該元素,而在這以前或以後,元素能夠不存在或者被銷燬。這個特色使得它特別適合用於遍歷一些巨大的或是無限的集合,好比幾個G的文件python

特色:express

  1. 訪問者不須要關心迭代器內部的結構,僅需經過next()方法不斷去取下一個內容
  2. 不能隨機訪問集合中的某個值 ,只能從頭至尾依次訪問
  3. 訪問到一半時不能往回退
  4. 便於循環比較大的數據集合,節省內存
  5. next()就至關於調用__next__(),for也是

iterable(可迭代)對象
支持每次返回本身所包含的一個成員的對象
對象實現了__iter__方法
  (1)序列類型,如 str,list,tuple,set
  (2)非序列類型,如 dict, file
  (3)用戶自定義的一些包含了__iter__()或__getitem__()方法的類函數

for循環可用於任何可迭代對象
  for循環開始時,會經過迭代協議傳遞給iter()內置函數,從而可以從可迭代對象中得到一個迭代器,返回的對象含有須要的next()方法spa

>>> 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

或者code

>>> 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

二、生成器

一個函數調用時返回一個迭代器,那這個函數就叫作生成器(generator);若是函數中包含yield語法,那這個函數就會變成生成器;可以用next()調用或for循環使用對象

def func():
    yield 1
    yield 2
    yield 3
    yield 4

上述代碼中:func是函數稱爲生成器,當執行此函數func()時會獲得一個迭代器。blog

>>> 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

利用生成器自定義rangeget

 def nrange(num):
    temp = -1
    while True:
        temp = temp + 1
        if temp >= num:
            return
        else:
            yield temp

列表解析和生成器表達式:

列表解析

列表解析是python迭代機制的一種應用,它經常使用於實現建立新的列表,所以要放置於[]中generator

語法:
[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)
相關文章
相關標籤/搜索