Python-迭代器與生成器

住的這個小區也建好幾年了,怎么周圍一直在裝修,鉆啊鉆啊。于是開大音樂,擋住鉆的聲音,周期性重復的聲音實在是亂人心緒。
邊工作邊讀書,Python Cookbook,將第4章讀完了,有的地方實在是太經典,不得不記在博客里,因為不想忘記~

  1. 代理迭代
    構建一個自定義容器對象,包含列表,元組或者其他可迭代對象,定義一個iter()方法,將迭代操作代理到容器內部的對象上。
class Node:
    def __init__(self,value):
        self._value = value
        self._children = []
    def __repr__(self):
        #使用{!r}和{!s}取得%r和%s的效果
        return 'Node({!r})'.format(self._value)
    def add_child(self,node):
        self._children.append(node)
    def __iter__(self):
        #返回一個列表的可迭代的對象
        return iter(self._children)
if __name__ == "__main__":
    root = Node(0)
    child1 = Node(1)
    child2 = Node(2)
    root.add_child(child1)
    root.add_child(child2)
    for ch in root:
        print(ch)```
2.  使用生成器創建迭代模式

def frange(start,stop,increment):
x = start
while x < stop:
yield x
x += increment
def countdown(n):
print("starting to count from ",n)
while n > 0:
yield n
n -= 1
print("done")```

  1. 關聯迭代器類
    實現深度優先搜索
    別急,后面更精彩……
class Node2:
    def __init__(self,value):
        self._value = value
        self._children = []
    def __repr__(self):
        return 'Node({!r})'.format(self._value)
    def add_child(self,node):
        self._children.append(node)
    def __iter__(self):
        return iter(self._children)
    def depth_first(self):
        #返回一個該類的實例,該類實現了iter和next方法
        return DepthFirstIterator(self)
class DepthFirstIterator(object):
    def __init__(self,start_node):
        self._node = start_node
        self._children_iter = None
        self._child_iter = None
    def __iter__(self):
        return self
    def __next__(self):
        #第一次next
        if self._children_iter is None:
            self._children_iter = iter(self._node)
            return self._node
        elif self._child_iter:
            try:
                nextchild = next(self._child_iter)
                return nextchild
            except StopIteration:
                self._child_iter = None
                return next(self)
        else:
            self._child_iter = next(self._children_iter).depth_first()
            return next(self)```
4. 實現迭代器協議

class Node:
def init(self,value):
self._value = value
self._children = []
def repr(self):
return 'Node({!r})'.format(self._value)
def add_child(self,node):
self._children.append(node)
def iter(self):
return iter(self._children)
def depth_first(self):
yield self
for c in self:
yield from c.depth_first()
if name == "main":
root = Node(0)
child1 = Node(1)
child2 = Node(2)
root.add_child(child1)
root.add_child(child2)
child1.add_child(Node(3))
child2.add_child(Node(4))
child1.add_child(Node(5))
for ch in root.depth_first():
print(ch)```

  1. reversed()函數返回反向的迭代器
    在自定義類上實現__reversed__()方法實現反向迭代
class Countdown:
    def __init__(self,start):
        self.start = start
    def __iter__(self):
        n = self.start
        while n > 0:
            yield n
            n -= 1
    def __reversed__(self):
        n = 1
        while n <= self.start:
            yield n
            n += 1```
6. itertools.islice()方法在迭代器和生成器上做切片操作

def count(n):
while True:
yield n
n += 1
c = count(0)
import itertools
gen = list(itertools.islice(c,10,20))
for x in gen:
print(x)
print(gen,"x",end="")```

  1. 使用itertools.dropwhile()函數來跳過某些遍歷對象
    丟棄原有序列中直到函數返回True之前的所有元素
from itertools import dropwhile
with open("/etc/passwd") as f:
    for line in dropwhile(lambda line:line.startswith("#"),f):
        print(line,end="")```
8. itertools.permutations()遍歷集合元素所有可能的排列組合

items = ['a','b','c']
from itertools import permutations
for p in permutations(items):
print(p)```

  1. enumerate()函數
from collections import defaultdict
#supply missing values
def word(filename):
    word_summary = defaultdict(list)
    #讀取文件行
    with open('myfile.txt','r') as f:
        lines = f.readlines()
    #提取出行與行的序號
    for idx,line in enumerate(lines):
        words = [w.strip().lower() for w in line.split()]
        for word in words:
            word_summary[word].append(idx)```
10. zip()同時迭代多個序列

a = [1,2,3]
b = [10,11,12]
c = ['x','y','z']
for i in zip(a,b,c):
print(i)```

  1. itertools.chain()在不同集合上元素的迭代
from itertools import chain
a = [1,2,3,4]
b = ['x','y','z']
for x in chain(a,b):
    print(x)```
12. 多層嵌套的序列展開
yield from在生成器函數中調用其他生成器作為子例程

from collections import Iterable
def flattern(items,ignore_type=(str,bytes)):
for x in items:
if isinstance(x,Iterable) and not isinstance(x,ignore_type):
#use another yield in a yield function
yield from flattern(x)
else:
yield x
items = [1 ,2,[3,4,[5,6],7],8]
for x in flattern(items):
print(x)```

  1. 順序序列的合并heapq.merge()
import heapq
a = [1,4,7,10]
b = [2,5,6,11]
for c in heapq.merge(a,b):
    print(c)```
14. 迭代來代替while循環

CHUNKSIZE = 8192
def reader(s):
while True:
data = s.recv(CHUNKSIZE)
if data == b'':
break
process_data(data)

這種可以使用iter()代替

iter函數創建一個迭代器,接受callable對象何一個標記

迭代一直到callable對象返回值和標記值相等為止

def reader2(s):
for chunk in iter(lambda: s.recv(CHUNKSIZE),b''):
pass```

  1. 創建一個類似于shell的數據管道
  • fnmatch模塊
    提供了shell風格的通配符wildcards,like * ? [ seq ] [ !seq ]
    • fnmatch.filter(names,pattern)
      return the subset of the list of names that match pattern
      same as [ n for n in names if fnmatch(n,pattern) ]
    • fnmatch.fnmatch(filename,pattern)
      test whether the filename string matches the pattern string.
    • fnmatch.fnmatchcase(filename,pattern)
      the comparison is case-sensitive
    • fnmatch.translate(pattern)
      return the shell-style pattern converted to a regular expression
  • 使用生成器函數來實現管道機制
    yield from將yield操作代理到父生成器上
    yield from it 返回生成器it所產生的所有值
import os
import fnmatch
import gzip
import bz2
import re
def gen_find(filepat,top):
    '''find all filenames and dirs that match a shell wildcards'''
    for path,dirlist,filelist in os.walk(top):
        for name in fnmatch.filter(filelist,filepat):
            #生成路徑
            yield os.path.join(path,name)
def gen_opener(filenames):
    '''open a sequence of filenames producing a file object
    and then closed it when proceeding to the next iteration'''
    for filename in filenames:
        if filename.endswith('.gz'):
            f = gzip.open(filename,'rt')
        elif filename.endswith('.bz2'):
            f = bz2.open(filename,'rt')
        else:
            f = open(filename,'rt')
        #生成文件對象
        yield f
        f.close()
def gen_concatenate(iterators):
    '''chain a sequence of iterators together into a single sequence'''
    # for every iterator yielding to generate a sequence
    for it in iterators:
        #when want to use yield in a yield function, use yield from
        yield from it
def gen_grep(pattern,lines):
    '''look for a regex pattern in a sequence of lines'''
    pat = re.compile(pattern)
    for line in lines:
        if pat.search(line):
            #生成匹配到的line
            yield line
#將這些函數連起來創建一個處理管道
lognames = gen_find('access-log*','www')
files = gen_opener(lognames)
lines = gen_concatenate(files)
pylines = gen_grep('python',lines)
for line in pylines:
    print(line)```
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,327評論 6 537
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,996評論 3 423
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,316評論 0 382
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,406評論 1 316
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,128評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,524評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,576評論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,759評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,310評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,065評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,249評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,821評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,479評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,909評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,140評論 1 290
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,984評論 3 395
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,228評論 2 375

推薦閱讀更多精彩內容