python 具有不同 next() 条件的生成器

python generator with different next() conditions

我需要一个 python 生成器来获取 pdf 文件中行的高度。 为此,我创建了一个生成器,它 returns 下一行的高度。

def height_generator(height):
    while height > 0:
        height -= 15
        yield(height)

目前为止效果很好。

但我需要不同的高度。例如,如果我的文件中需要一个新段落,我需要将高度降低 20 而不是 15。

为了得到这个,我想定义,如果我想要一个新的行或一个新的段落,当我调用我的生成器时。

我做了这样的事情:

def height_generator(height):
    while height > 0:
        def spacer(height, a):
            if a == 1:
                height -= 15
                yield(height)
            elif a ==2:
                height -= 20
                yield(height)

但它不起作用。

您在 while 循环中定义一个函数,这只会使您的代码无限循环。

您需要 send(a) 生成器告诉它该做什么。例如

def height_generator(height):
    while height > 0:
        a = yield height
        if a == 1:
            height -= 15
        else:
            height -= 20

g = height_generator(100)
g.next()
print g.send(1) # 85
print g.send(2) # 65
print g.send(1) # 50

yield 不仅是生成器向其调用者生成值的一种方式,还可以用于向生成器发送值。传递给 send 的参数将是表达式 yield height 的值。更多详情,请阅读PEP 255

为什么不做这样的事情呢?:

def height_generator(height):
    while height > 0:
        a= yield height
        if a == 'nl':
            height -= 15
        elif a == 'np':
            height -= 20