import sections

In [3]:
from collections.abc import Container, Iterable, Iterator, Generator

yield example


In [53]:
class GCls(object):
    def __iter__(self):
        return g_t()
    
def g_t():
    try:
        try:
            yield 1
#             c['d']
#             1/0
            yield 2
        except ZeroDivisionError:
            yield 3
            yield 4
            raise
        else:
            yield 10
        finally:
            yield 11

    except:
        yield 12

    finally:
        yield None
    
t = GCls()
# isinstance(t, Iterable)


Out[53]:
True

In [54]:
[x for x in t]


Out[54]:
[1, 2, 10, 11, None]

itert example 1


In [24]:
class ItNext(object):
    
    def __init__(self, begin, end):
        self.begin = begin
        self.end = end
        self.con = 0
    
    def __repr__(self):
        return f'Class with begin value: {self.con}'
    
    def __iter__(self):
        print(f'iter{self.__dict__}')
        return self  # 返回 ItNext 实例自身
    
    def __next__(self):
        self.con += 1
        if  self.begin == self.end:
            raise StopIteration
        self.begin +=1
        
        print(f'next{self.con}-->{self.__dict__}')
        return self.begin  #  返回 新的 ItNext  属性值 self.begin 提供给next
    
    
i = ItNext(0, 9)

[x for x in i]


iter{'begin': 0, 'end': 9, 'con': 0}
__next__
next1-->{'begin': 1, 'end': 9, 'con': 1}
__next__
next2-->{'begin': 2, 'end': 9, 'con': 2}
__next__
next3-->{'begin': 3, 'end': 9, 'con': 3}
__next__
next4-->{'begin': 4, 'end': 9, 'con': 4}
__next__
next5-->{'begin': 5, 'end': 9, 'con': 5}
__next__
next6-->{'begin': 6, 'end': 9, 'con': 6}
__next__
next7-->{'begin': 7, 'end': 9, 'con': 7}
__next__
next8-->{'begin': 8, 'end': 9, 'con': 8}
__next__
next9-->{'begin': 9, 'end': 9, 'con': 9}
__next__
Out[24]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]

In [46]:
def huithree(end):
    lst = [1]
    for _ in range(end):
        yield lst
        lst = [lst[i] + lst[i+1] for  i in range(len(lst)-1)]
        lst.insert(0,1)
        lst.append(1)
        
[x for x in huithree(10)]


Out[46]:
[[1],
 [1, 1],
 [1, 2, 1],
 [1, 3, 3, 1],
 [1, 4, 6, 4, 1],
 [1, 5, 10, 10, 5, 1],
 [1, 6, 15, 20, 15, 6, 1],
 [1, 7, 21, 35, 35, 21, 7, 1],
 [1, 8, 28, 56, 70, 56, 28, 8, 1],
 [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]]

In [47]:
import os
import fnmatch
import gzip
import bz2
import re

def gen_find(filepat, top):
    '''
    Find all filenames in a directory tree that match a shell wildcard pattern
    '''
    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 one at a time producing a file object.
    The file is closed immediately 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 it in iterators:
        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):
            yield line
file_names = gen_find('hangzhou.sf.hu_base*', 'D:\\Git\\hangzhou_sf_hu\\bak')
files = gen_opener(file_names)
lines = gen_concatenate(files)
pylines = gen_grep('.DS_Store', lines)

[f for f in pylines]


---------------------------------------------------------------------------
UnicodeDecodeError                        Traceback (most recent call last)
<ipython-input-47-9fb435efbe8e> in <module>()
     48 pylines = gen_grep('.DS_Store', lines)
     49 
---> 50 [f for f in pylines]

<ipython-input-47-9fb435efbe8e> in <listcomp>(.0)
     48 pylines = gen_grep('.DS_Store', lines)
     49 
---> 50 [f for f in pylines]

<ipython-input-47-9fb435efbe8e> in gen_grep(pattern, lines)
     40     '''
     41     pat = re.compile(pattern)
---> 42     for line in lines:
     43         if pat.search(line):
     44             yield line

<ipython-input-47-9fb435efbe8e> in gen_concatenate(iterators)
     33     '''
     34     for it in iterators:
---> 35         yield from it
     36 
     37 def gen_grep(pattern, lines):

UnicodeDecodeError: 'gbk' codec can't decode byte 0xea in position 117: illegal multibyte sequence