In [3]:
from collections.abc import Container, Iterable, Iterator, Generator
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]:
In [54]:
[x for x in t]
Out[54]:
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]
Out[24]:
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]:
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]