【python 第七日】迭代器类和生成器进阶 __next__ __iter__

迭代器中的throw

放出异常,消耗一个yield

def gen():
    while True: 
        try:
            yield 'normal value'
            yield 'normal value 2'
            print('here')
        except ValueError:
            print('we got ValueError here')
        except TypeError:
            break

g=gen()
print(next(g))
print(g.throw(ValueError))
print(next(g))
print(g.throw(TypeError))

#输出
normal value
we got ValueError here
normal value   #第二个抛出异常,到这里,消耗了一个yield
normal value 2
Traceback (most recent call last):
  File "h.py", line 15, in <module>
    print(g.throw(TypeError))
StopIteration

迭代器中的yield from <iterator>

def inner():
    for i in range(10):
        yield i
def outer():
    g_inner=inner()    #这是一个生成器
    while True:
        res = g_inner.send(None)
        yield res

g_outer=outer()
while True:
    try:
        print(g_outer.send(None))
    except StopIteration:
        break

#此时,我们可以采用yield from语句来减少我么你的工作量。 def outer2(): yield from inner() #当然 ,yield from语句的重点是帮我们自动处理内外层之间的异常问题,这里有2篇写的很好的文章,所以我就不再啰嗦了。

杨辉三角形

没用生成器函数,用的迭代器类,一种是直接写在next中,另外一个种是写到生成器yield,一定要加while True ,否则只有一个yield

import  logging
import sys

logging.basicConfig(
level= logging.INFO,
stream = sys.stdout
)
class Fib:
def __init__(self,max):
print("__init__开始")
self.max = max
def __iter__(self):
print("__iter__开始")
self.l = [1]
print("__iter__结束")
return self

def __next__(self):

print("__next__开始,此时l为:",self.l,len(self.l))
if len(self.l) > self.max :
raise StopIteration
x = self.l
self.new_l = [1]
for i in range(len(self.l)):
if i < len(self.l) -1 :
self.new_l.append(self.l[i]+self.l[i+1])
else:
self.new_l.append(self.l[i])
self.l = self.new_l
return x

class Fib1:
def __init__(self,max):
print("__init__开始")
self.max = max


def __iter__(self):
print("__iter__开始")
self.ge = self.yie()
self.l = [1]
print("__iter__结束")
return self

def yie(self):
while True: # 一定要加while True
print("__yie__开始,此时l为:", self.l, len(self.l))
if len(self.l) > self.max:
raise StopIteration
yield self.l
self.new_l = [1]
for i in range(len(self.l)):
if i < len(self.l) - 1:
self.new_l.append(self.l[i] + self.l[i + 1])
else:
self.new_l.append(self.l[i])
self.l = self.new_l

def __next__(self):
logging.info("进入__next__,此时self.l:%s self.max:%s self.self.ge:%s"%(self.l, self.max, self.ge))
return next(self.ge)

a = iter(Fib1(10))
print(a)
print(next(a))
print(next(a))
print(next(a))
print(next(a))


#返回结果

__init__开始
__iter__开始
__iter__结束
<__main__.Fib1 object at 0x02C914D0>
INFO:root:进入__next__,此时self.l:[1] self.max:10 self.self.ge:<generator object Fib1.yie at 0x02C8F330>
__yie__开始,此时l为: [1] 1
[1]
INFO:root:进入__next__,此时self.l:[1] self.max:10 self.self.ge:<generator object Fib1.yie at 0x02C8F330>
__yie__开始,此时l为: [1, 1] 2
[1, 1]
INFO:root:进入__next__,此时self.l:[1, 1] self.max:10 self.self.ge:<generator object Fib1.yie at 0x02C8F330>
__yie__开始,此时l为: [1, 2, 1] 3
[1, 2, 1]
INFO:root:进入__next__,此时self.l:[1, 2, 1] self.max:10 self.self.ge:<generator object Fib1.yie at 0x02C8F330>
__yie__开始,此时l为: [1, 3, 3, 1] 4
[1, 3, 3, 1]


#这里有未解决问题,用列表生成器生成杨辉三角的形式,这里不会赋值,求大神指教,17741779847
l = [1]
max =10
for i in range(1,11):
# new = [1]
for j in range(len(l)-1,0,-1):
l[j] = l[j] +l[j-1]
l.append(1)
print(l)
l = [1]
a = ([ l for j in range(len(l)-1, 0,-1) ] for i in range(max)) #这里两个问题,第一个如何生成类的生成器,第二个如何用列表生成器表示杨辉三角形,应该是2曾的

print(next(a))
print(next(a))
print(next(a))
posted @ 2019-01-08 14:17  周sir搞人工  阅读(197)  评论(0编辑  收藏  举报